我正在尝试使用 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/