Javascript – Loop promises one by one with a sleep in between

//Async task

let asyncTask = (input) => {

  //Below is a sample

  returnnewPromise((resolve, reject) => {

    console.log('Task no: '+input)

    resolve();

  })

};


//Loop function that throttles async tasks - one by one and with an sleep interval.

let loop = (count, oncompletion) => {

  //Execute main code and recurse if count > 0

  asyncTask(count).then(

    resonse=> {

    count--

    if(count) {

      setTimeout( ()=>loop(count), loopInterval );

    } else

      onCompletion();

  },

  error=> {

    console.log('Some error happend.');

  });

};


//This function is called back after looping through all async tasks.

let onCompletion = () => {

  console.log('Completed');

}


//Run the loop

let loopCount = 5;

let loopInterval = 1000;

loop(loopCount, loopInterval, onCompletion);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s