Sequential promise loop with delay

前端 未结 1 1842
故里飘歌
故里飘歌 2021-01-17 02:16

I\'m attempting to load an array of \"requests\" sequentially each one separated by a delay.

I\'m using promises but for some reasons I\'m having issues with the req

相关标签:
1条回答
  • 2021-01-17 02:36

    The issue is that you're not updating sequence to include any of the successive operations, so all of them are chaining off of that original resolved promise. There's nothing there to delay any of them, so they execute right away.

    You should be able to remedy this simply by updating the sequence variable on every loop, so you're chaining off the end of the chain:

    //object I need to use to construct requests
    var batches = [of_objects];
    var sequence = Promise.resolve();
    var self = this;
    
    batches.forEach(function (batch){
        sequence = sequence            // <-- here
            //Function returns promise
            .then( function(){
                return self._createRequestPromise(batch); //this runs first 5x
            })
            //callback so we can update, returns nothing
            .then(callback)
            //add 3 sec timeout before next request
            .then(function(){
                return new Promise(function (resolve, reject){
                    setTimeout(resolve, 3000); //this runs after 5x
                });
            });
    });
    
    return sequence;
    

    Personally, I try to avoid overwriting variables, so an alternate way to do this without variable reassignment is to use .reduce():

    //object I need to use to construct requests
    var batches = [of_objects];
    var self = this;
    
    return batches.reduce(function (last, batch){
        return last
            //Function returns promise
            .then( function(){
                return self._createRequestPromise(batch); //this runs first 5x
            })
            //callback so we can update, returns nothing
            .then(callback)
            //add 3 sec timeout before next request
            .then(function(){
                return new Promise(function (resolve, reject){
                    setTimeout(resolve, 3000); //this runs after 5x
                });
            });
    }, Promise.resolve());
    
    0 讨论(0)
提交回复
热议问题