How to synchronize a sequence of promises?

后端 未结 6 813
醉梦人生
醉梦人生 2020-11-22 09:05

I have an array of promise objects that must be resolved in the same sequence in which they are listed in the array, i.e. we cannot attempt resolving an element till the pre

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:51

    You can't simply run X async operations and then want them to be resolved in an order.

    The correct way to do something like this is to run the new async operation only after the one before was resolved:

    doSomethingAsync().then(function(){
       doSomethingAsync2().then(function(){
           doSomethingAsync3();
           .......
       });
    });
    

    Edit
    Seems like you want to wait for all promises and then invoke their callbacks in a specific order. Something like this:

    var callbackArr = [];
    var promiseArr = [];
    promiseArr.push(doSomethingAsync());
    callbackArr.push(doSomethingAsyncCallback);
    promiseArr.push(doSomethingAsync1());
    callbackArr.push(doSomethingAsync1Callback);
    .........
    promiseArr.push(doSomethingAsyncN());
    callbackArr.push(doSomethingAsyncNCallback);
    

    and then:

    $.when(promiseArr).done(function(promise){
        while(callbackArr.length > 0)
        {
           callbackArr.pop()(promise);
        }
    });
    

    The problems that can occur with this is when one or more promises fail.

提交回复
热议问题