isiaatz
isiaatz

Reputation: 1145

Wait until all promises finished

How can I know when all promises inside the for loop finished executing? Is there a better way to do it?

for (let index = 0; index < array.length; index++) {
  request(array[index], function (error, response, body) {
    promise1().then(result1 => {
      if (result1 !== 0) {
        promise2().then(result2 => {
          promise3(result2);
        }
      } else {
        promise3(result1);
      }
    });
  });
}

console.log('all promises finished');

Upvotes: 1

Views: 85

Answers (2)

Akash Tomar
Akash Tomar

Reputation: 980

You can keep adding the promises you create in a list inside the for loop.

Once you are done with your loop, you can register a Promise.all method.

let list_of_promises = [];

for(...) {
    list_of_promises.push(
        new Promise(function(resolve, reject)) {
            ...
        }
    )
}

Promise.all(list_of_promises).then(function(data)) {
    ...
}.catch(function(err) {
    ...
});

If all your promises get resolved, .then method will be called.

Note: Even if one of your promise fails, it will go inside the .catch method.

Upvotes: 2

AKX
AKX

Reputation: 169378

This is made easier by transforming the code to use async/await to map the items into promises, then using the standard Promise.all() function to wait for all of the promises to resolve:

// promisified request()
const requestP = item =>
  new Promise((resolve, reject) => {
    request(item, (error, response, body) => {
      if (error) return reject(error);
      resolve({ response, body });
    });
  });

const processItem = async item => {
  const { response, body } = await requestP(item);
  const result1 = await promise1(/* this probably uses response or body? */);
  if (result1 !== 0) {
    const result2 = await promise2();
    return await promise3(result2);
  } else {
    return await promise3(result1);
  }
};

const promises = array.map(processItem);

Promise.all(promises).then(() => {
  console.log("all promises finished");
});

Upvotes: 2

Related Questions