在我的節點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