How do I sequentially chain promises with angularjs $q?

前端 未结 7 2199
一向
一向 2020-11-30 07:39

In the promise library Q, you can do the following to sequentially chain promises:

var items = [\'one\', \'two\', \'three\'];
var chain = Q();
items         


        
7条回答
  •  时光取名叫无心
    2020-11-30 08:21

    Simply use the $q.when() function:

    var items = ['one', 'two', 'three'];
    var chain = $q.when();
    items.forEach(function (el) {
      chain = chain.then(foo(el));
    });
    return chain;
    

    Note: foo must be a factory, e.g.

    function setTimeoutPromise(ms) {
      var defer = $q.defer();
      setTimeout(defer.resolve, ms);
      return defer.promise;
    }
    
    function foo(item, ms) {
      return function() {
        return setTimeoutPromise(ms).then(function () {
          console.log(item);
        });
      };
    }
    
    var items = ['one', 'two', 'three'];
    var chain = $q.when();
    items.forEach(function (el, i) {
      chain = chain.then(foo(el, (items.length - i)*1000));
    });
    return chain;
    

提交回复
热议问题