How can I sequentially chain promises using bluebirdjs?

后端 未结 2 505
被撕碎了的回忆
被撕碎了的回忆 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 18:50

    The thing that confused me most is that the async function being chained needs to return a function that returns a promise. Here's an example:

    function setTimeoutPromise(ms) {
      return new Promise(function (resolve) {
        setTimeout(resolve, ms);
      });
    }
    
    function foo(item, ms) {
      return function() {
        return setTimeoutPromise(ms).then(function () {
          console.log(item);
        });
      };
    }
    
    var items = ['one', 'two', 'three'];
    
    function bar() {
      var chain = Promise.resolve();
      items.forEach(function (el, i) {
        chain = chain.then(foo(el, (items.length - i)*1000));
      });
      return chain;
    }
    
    bar().then(function () {
      console.log('done');
    });
    

    Notice that foo returns a function that returns a promise. foo() does not return a promise directly.

    See this Live Demo

提交回复
热议问题