2017-05-24 83 views
0

我正在尝试使用节点和快车制作API。 这是创建用户的功能。如何避免级联承诺和catchs?

我不确定我是否正确处理错误,因为异步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}); 
    }) 
} 

有没有做到这一点最好方法是什么?

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

谢谢。

+0

可以返回当时的语句中一个新的承诺... –

+0

看一看https://stackoverflow.com/questions/27715275/whats-该差之间,返回值有或承诺,解决从 - 然后 –

回答

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

你可以链中的承诺...