顺序执行Promise [英] Sequential execution of Promise
问题描述
我实现了以下promise函数,例如
I have following promise functions implemented like
return new Promise(function(resolve, reject) { //logic });
- cart.getBasket(req)
- cart.updateBasket(req)
- cart.updateDefaultShipment(req)
- cart.getBasketObject(basket)
当前,我使用
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
返回每个承诺的值执行.
I read about Promise.each
and thought of using it as the flow of my logic has to be sequential but when I use Promise.each
it doesn't work as expected because I saw that inner function of each
returns value of every promise execution.
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
链的功能,即拥有更清洁的链.
So, is there any cleaner way available to achieve what am doing with .then
chain i.e have a cleaner chain.
此外,在顺序执行诺言中,下一个诺言函数是否有可能获得已执行的上一个诺言的返回值.
Also, is it possible in sequential promise execution that the next promise function gets the return value of the previous promise which got executed.
PS:承诺的阵列长度会事先知道.
PS : Promise array length will know beforehand.
推荐答案
您可以在不增加嵌套的情况下对Promise进行排序:
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);
});
});
从.then()
返回诺言会自动将其链接到父诺言,这使您可以在父诺言上使用.then()
处理程序,而不是使用更深层的嵌套来继续执行序列.
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
这篇关于顺序执行Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!