How do I sequentially chain promises with angularjs $q?

前端 未结 7 2272
一向
一向 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

    Your answer is correct. However, I thought I'd provide an alternative. You may be interested in $q.serial if you find yourself serially chaining promises often.

    var items = ['one', 'two', 'three'];
    var tasks = items.map(function (el) {
      return function () { foo(el, (items.length - i)*1000)); });
    });
    
    $q.serial(tasks);
    
    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);
        });
      };
    }
    

提交回复
热议问题