How can I sequentially chain promises using bluebirdjs?

后端 未结 2 507
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 18:13

Promise.all() doesn\'t guarantee that promises will be resolved in order. How can this be done?

2条回答
  •  长情又很酷
    2020-12-06 19:00

    Since you're using Bluebird JS, this can be actually done in a simple way.

    In version 2.0, Bluebird introduced the Promise.each method that does this, for looping a then is simple enough, but since it is so common and got requested time after time eventually it was added as its own method.

    function foo(item, ms){ // note bluebird has a delay method
        return Promise.delay(ms, item).then(console.log.bind(console))
    }
    
    var items = ['one', 'two', 'three'];
    
    Promise.each(items, function(item, i){
        return foo(item, (items.length - i) * 1000)
    });
    

    Which produces the same result as the other answer, only with less lines of code and it also lets Bluebird perform optimizations on the iteration.

提交回复
热议问题