Salar
Salar

Reputation: 5499

Execute an Array of promises sequentially without using async/await

Lets say I have an array of promises. Each element of my array is a knex.js query builder and is ready to be executed and returns a promise.

How can I run each element of this array sequentially. The array is built dynamically.

let promisesArray = [q1,q2,q3] ;

Each q is not a promise by itself but it will return a promise upon execution.

Upvotes: 6

Views: 1558

Answers (5)

swaroop ghosh
swaroop ghosh

Reputation: 11

If you're using bluebird, you can use Promise.map with concurrency set to 1.

await Promise.map(arrayOfObj, async (obj) => {
    await this.someOperation();
  },
  {concurrency: 1}
);

Upvotes: 0

Amin Fazlali
Amin Fazlali

Reputation: 1237

Here could be a possible option:

let p = Promise.resolve([]);
promisesArray.forEach(q => {
  p = p.then(responses => {
    //based on the nature of each q, to start execution
    //use either q().then() or q.then()
    return q().then(response => {
      //Any further logic can be here.
      console.log(response);
      return responses.concat([response]);
    })
  })
})

p.then(responses => {
  // here you have all of the responses.
})

Upvotes: 5

Khaled Osman
Khaled Osman

Reputation: 1467

You can use Array.reduce to reduce the Array into one promise that chains them one after another

let promisesArray = [q1,q2,q3] ;

function runSequentially(promiseArr) {
  return promiseArr.reduce((accum, p) => accum.then(p), Promise.resolve())
}

//Example, this prints.. 1, 2, 3 then "done".
runSequentially([Promise.resolve(1).then(console.log), Promise.resolve(2).then(console.log), Promise.resolve(3).then(console.log)]).then(() => console.log("done"))

Upvotes: 1

Charlie
Charlie

Reputation: 23768

Based on your claim that q1, q2, q3 are "knex.js query builder and is ready to be executed and returns a promise", get a function to execute itself with the next index when the promise is resolved. Call it with 0 first.

function awaitPromise(arr, idx) {

   arr[idx]().then(function(res) {

       console.log(res);

       if (idx < arr.length - 1)      
           awaitPromise(arr, idx + 1);
   })
}

Upvotes: 0

Sreehari
Sreehari

Reputation: 1370

I can think of bluebird promise, which should solve your issue. Keeping the concurrency value to 1, should execute promises sequentially.

    var Promise = require("bluebird");
    Promise.map([q1,q2,q3], {concurrency: 1})

Upvotes: 0

Related Questions