Promise的顺序执行

时间:2016-04-15 14:29:40

标签: javascript node.js express promise bluebird

我有以下承诺功能,如

return new Promise(function(resolve, reject) { //logic });
  1. cart.getBasket(REQ)
  2. cart.updateBasket(REQ)
  3. cart.updateDefaultShipment(REQ)
  4. cart.getBasketObject(篮法)
  5. 目前我使用

    执行代码
       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数组长度将事先知道。

1 个答案:

答案 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