Asynchronous Loop of jQuery Deferreds (promises)

后端 未结 6 1942
执笔经年
执笔经年 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条回答
  •  萌比男神i
    2020-12-08 08:56

    Interesting challenge indeed. What I have come up with is a recursive function that accepts a list and an optional start index.

    Here is a link to the jsFiddle that I have tested with a few different list lengths and intervals.

    I'm assuming you have a list of functions that return promises (not a list of numbers). If you do have a list of numbers you would change this part

    $.when(tasks[index]()).then(function(){
        deferredSequentialDo(tasks, index + 1);
    });
    

    to this

    /* Proxy is a method that accepts the value from the list
       and returns a function that utilizes said value
       and returns a promise  */
    var deferredFunction = myFunctionProxy(tasks[index]);
    
    $.when(tasks[index]()).then(function(){
        deferredSequentialDo(tasks, index + 1);
    });
    

    I'm not sure how big your list of functions could be but just be aware that the browser will hold on to the resources from the first deferredSequentialDo call until they are all finished.

提交回复
热议问题