【问题标题】:How to avoid cascading promises and catchs?如何避免级联的承诺和捕获?
【发布时间】:2017-10-24 20:44:33
【问题描述】:

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

我不确定我是否正确处理错误,因为异步 mongodb 函数,我感觉自己正处于“承诺地狱”中。接下来我要做的是获取插入用户的 id,我想这将是另一个承诺,另一个需要处理的错误......

  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});
    })
}

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

顺便说一句,我不能使用验证库和猫鼬。

谢谢。

【问题讨论】:

标签: javascript node.js mongodb error-handling promise


【解决方案1】:
  // 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"]
});

你可以链接承诺...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2015-02-18
    • 2019-09-18
    • 2017-10-07
    • 2021-04-07
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多