在我的节点js应用程序中,我试图创建一个需要几个异步步骤的注册路径。在早期阶段,有一种情况是我想停下来,然后回复一条消息,但我对混合条件融入承诺感到困惑。有条件地退出承诺链而不会抛出错误
我的具体问题是在下面的伪代码注释:
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);
});
});
我怎么能有条件地“挽救”是第一个承诺完成后,未抛出错误?
https://www.npmjs.com/package/qx#breakwith-and-endfunction – SLaks
的'async'实用程序可能会来得心应手那种控制流在那里你做了很多异步工作,但仍然想要控制流和可读性(不是以回调地狱结束) :http://caolan.github.io/async/ – topheman
@topheman - 没有理由从承诺转移到异步库。承诺有很多控制来解决这个问题。 – jfriend00