javascript - 如何避免级联的 promise 和捕获?

标签 javascript node.js mongodb error-handling promise

我正在尝试使用 Node 和 Express 制作 API。 这是创建用户的函数。

我不确定我是否正确处理错误,由于异步 mongodb 函数,我感觉自己处于“ promise hell ”中。我要做的下一件事是获取插入的用户的 id,我想这将是另一个 promise ,另一个需要处理的错误...

  exports.create = function(req, res, next) {
  var errors = [];
  var userData = req.body;

  // exit if the user didn't fill all fields
  var requiredFields = ['first_name',
                        'last_name',
                        'login',
                        'email',
                        'password',
                        'sex'];
  requiredFields.forEach(function(elem) {
    if (!userData.hasOwnProperty(elem))
      errors.push('The field \'' + elem + '\' is missing');
  });
  if (errors.length !== 0)
    res.status(400).json({errors: errors});

  // check if the user or the login are already in use
  db.connection.collection(COLLECTION_NAME).findOne({ $or: [
                              { email: userData.email },
                              { login: userData.login }
                            ]})
    .then(function(data) {
      // if there is no user (null) we can create it
      if (data === null) {
        db.collection(COLLECTION_NAME).insertOne(userData).then(function (data) {
          res.status(201).json("success");
        }, function (err) {
          res.status(400).json({errors: ["DB error: cannot create user"]});
        })
      } else {
        errors.push('An user is already registered with this email or this login.');
        if (errors.length !== 0)
          res.status(400).json({errors: errors});
      }
    }, function (err) {
      res.status(400).json({errors: errors});
    })
}

有没有最好的方法来做到这一点?

顺便说一句,我不能使用验证库,也不能使用 Mongoose 。

谢谢。

最佳答案

  // check if the user or the login are already in use
  db.connection.collection(COLLECTION_NAME).findOne({
                        $or: [
                          { email: userData.email },
                          { login: userData.login }
 ]})
.then(function(data) {
  // if there is no user (null) we can create it
      if (data === null) {  
         return  db.collection(COLLECTION_NAME).insertOne(userData)
     }else{ 
         return new Promise.reject(0);//throw the error
     }
 }).then(function (data) {
      res.status(201).json("success");
 }, function (err) {
      res.status(400).json({errors: ["DB error: cannot create user"]
});

你可以将 promise 串联起来......

关于javascript - 如何避免级联的 promise 和捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44159503/

相关文章:

javascript - 无论如何要让 document.write 工作而不删除整个页面?

javascript - 是否可以使用 jquery 选择带有 vendor 前缀的属性?

node.js - 启动应用程序上的 Electron 闪屏

node.js - 我收到 "io is not defined"错误

mongodb - Loopback mongodb-connector principalId 存储为字符串

node.js - 如何在 MongoDB collection.find() 上获得回调

mongodb - 在 mongodb 集合中查找所有按字段最新且与另一个字段不同的文档

javascript - Wordpress 下拉菜单

javascript - 如何在 Vue 的插件中添加全局函数,如 Create、Methods、Mounted?

node.js - Mongoose 在保存之前更新模型