Asynchronous Loop of jQuery Deferreds (promises)

后端 未结 6 1938
执笔经年
执笔经年 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 08:48

    You can create a resolved $.Deferred and just add to the chain with each iteration:

    var dfd = $.Deferred().resolve();
    tasks.forEach(function(task){
        dfd = dfd.then(function(){
            return doTask(task);
        });
    });
    

    Step by step the following is happening:

    //begin the chain by resolving a new $.Deferred
    var dfd = $.Deferred().resolve();
    
    // use a forEach to create a closure freezing task
    tasks.forEach(function(task){
    
        // add to the $.Deferred chain with $.then() and re-assign
        dfd = dfd.then(function(){
    
            // perform async operation and return its promise
            return doTask(task);
        });
    
    });
    

    Personally, I find this cleaner than recursion and more familiar than $().queue (jQuery API for $().queue is confusing as it is designed for animations, it is also likely you are using $.Deferred's in other places in your code). It also has the benefits of standard transfer of results down the waterfall through resolve() in the async operation and allowing the attachment of a $.done property.

    Here it is in a jsFiddle

提交回复
热议问题