在我的 Node js 应用程序中,我尝试创建一个需要几个异步步骤的注册路由。在早期步骤中,有一个条件我想停止并只返回一条消息,但我对将条件混合到 promise 中感到困惑。
我的具体问题在以下伪代码的注释中:
router.post('/register', function(req, res, next) {
var identity = req.body.identity;
var password = req.body.password;
// can't register without a reservation
hasReservation(identity).then(function(hasReservation) {
if (hasReservation) { return register(identity, password); }
else {
// stuck here: I want to say:
res.json({ registered: false, reason: "missing reservation" });
// and then I want to stop further promises
// but this isn't an error, I don't want to throw an error here
}
}).then(function(user) {
// in my app, registering an existing user is okay
// I just want to reset a few things about the user and save
// but I don't want to be here if there's no reservation
if (user) {
user.foo = 'bar';
return user.save().then(function() { return user; });
} else {
return register(identity, password);
}
}).then(function(user) {
// I want to do more asynch stuff here
}).then(function(result) {
res.json(result);
}).catch(function(error) {
res.status(500).json(error);
});
});
如何在第一个 promise 完成后有条件地“退出”而不抛出错误?
最佳答案
如果register(identity,password)返回一个promise,您可以按如下方式重新组织您的代码:
router.post('/register', function(req, res, next) {
var identity = req.body.identity;
var password = req.body.password;
// can't register without a reservation
hasReservation(identity)
.then(function(hasReservation) {
if (hasReservation) {
return register(identity, password)
.then(function(user) {
// in my app, registering an existing user is okay
// I just want to reset a few things about the user and save
// but I don't want to be here if there's no reservation
if (user) {
user.foo = 'bar';
return user.save().then(function() { return user; });
} else {
return register(identity, password);
}
})
.then(function(user) {
// I want to do more asynch stuff here
})
.then(function(result) {
res.json(result);
})
} else {
// stuck here: I want to say:
res.json({ registered: false, reason: "missing reservation" });
// and then I want to stop further promises
// but this isn't an error, I don't want to throw an error here
}
})
.catch(function(error) {
res.status(500).json(error);
});
});
否则,如果 register(..) 仅返回一个值,则将 register(...) 的第一个实例包装在 Promise.resolve 中
return Promise.resolve(register(identity, password))
关于javascript - 有条件地提前退出一系列 promise 而不抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668105/