我有以下承诺功能,如
return new Promise(function(resolve, reject) { //logic });
目前我使用
执行代码 app.post('/Billing', function(req, res) {
cart.getBasket(req).then(function(basket) {
cart.updateBasket(req).then(function() {
cart.updateDefaultShipment(req).then(function(basket) {
cart.getBasketObject(basket).then(function(basketObj) {
res.render('billing', {
basket: basketObj
});
});
});
});
}).catch(function(error) {
console.log(error);
});
});
我读到Promise.each
并考虑使用它,因为我的逻辑流程必须是顺序的,但是当我使用Promise.each
时,它并没有按预期工作,因为我看到inner function of each
1}}返回每个promise执行的值。
app.post('/Billing', function(req, res) {
var asyncCalls = [cart.getBasket(req), cart.updateBasket(req), cart.updateDefaultShipment(req), cart.getBasketObject(basket)];
Promise.each(asyncCalls, function(basketObj){
res.render('billing', {
basket: basketObj
});
});
});
那么,有没有更清晰的方法可以实现.then
链的做法,即拥有更清洁的链条。
此外,在顺序承诺执行中是否有可能下一个promise函数获取前一个promise的返回值。
PS:Promise数组长度将事先知道。
答案 0 :(得分:3)
You can sequence promises without the ever increasing nesting like this:
app.post('/Billing', function(req, res) {
cart.getBasket(req).then(function(basket) {
return cart.updateBasket(req);
}).then(function() {
return cart.updateDefaultShipment(req);
}).then(function(basket) {
return cart.getBasketObject(basket);
}).then(function(basketObj) {
res.render('billing', {basket: basketObj});
}).catch(function(error) {
console.log(error);
res.sendStatus(500);
});
});
Returning a promise from a .then()
autoamtically chains it to the parent promise which allows you to use a .then()
handler on the parent promise rather than using deeper nesting to continue the sequence.
This automatically passed the results of the prior promise down the chain to the next operation, but it doesn't pass all prior results to subsequent promises. If you need other prior results, you can see various ways to do that here: How to chain and share prior results with Promises