Asynchronous Loop of jQuery Deferreds (promises)

后端 未结 6 1920
执笔经年
执笔经年 2020-12-08 08:21

I am trying to create what I think is referred to as a \"Waterfall\". I want to sequentially process an array of async functions (jQuery promises).

Here\'s a contr

6条回答
  •  时光说笑
    2020-12-08 09:00

    Have a look at the $.when and then methods for running deferreds.

    Waterfalls are used to pipe return values from one deferred to the next, in series. It would look something like this.

    function doTask (taskNum) {
      var dfd = $.Deferred(),
          time = Math.floor(Math.random() * 3000);
    
      console.log("running task " + taskNum);
    
      setTimeout(function(){
          console.log(taskNum + " completed");
          dfd.resolve(taskNum + 1);
      }, time)
    
      return dfd.promise();
    }
    
    var tasks = [1, 2, 3];
    
    tasks
      .slice(1)
      .reduce(function(chain) { return chain.then(doTask); }, doTask(tasks[0]))
      .then(function() { console.log("all done"); });
    

    Note the argument passed to resolve. That gets passed to the next function in the chain. If you just want to run them in series without piping in arguments, you can take that out and change the reduce call to .reduce(function(chain, taskNum) { return chain.then(doTask.bind(null, taskNum)); }, doTask(tasks[0]));

    And in parallel it would look like this:

    var tasks = [1,2,3].map(function(task) { return doTask(task); });
    
    $.when.apply(null, tasks).then(function() { 
        console.log(arguments); // Will equal the values passed to resolve, in order of execution.
    });
    

提交回复
热议问题