-2

Good day, I'm learning async await JavaScript and i just started. How to check if all my promises all done? just little confuse about that part. check my code if i'm doing it right. also i'll be happy if there are explanation. TIA

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

function resolveAfter5Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 5000);
  });
}

function resolveAfter7Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 7000);
  });
}

async function checkIfAllFunctionDone() {

    console.time('main')
  const result = await [resolveAfter2Seconds(), resolveAfter5Seconds(), resolveAfter7Seconds()];
  console.log(result);
    console.timeEnd('main')
  if(result){
    console.log('start saving...')
  }
}

checkIfAllFunctionDone();
Strywyr
  • 242
  • 15

1 Answers1

0

You push individual promises into an array, then you promise.all that array. The results are indexed in the same order as the original array of promises.

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result.status)));

See Promise.all() and Promise.allSettled().

The Promise.all() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.

The Promise.allSettled() static method takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • is it possible to do after `Promise.allSettled(promises)` then i do it like `then((results) => { insertfunctionhere })` ? is this okay to do? – Strywyr Apr 15 '23 at 01:43
  • or should i check `result.forEach` if all result status is 200 then i do the `insertfunction`? – Strywyr Apr 15 '23 at 01:44
  • Using the `async` style you can do `let results = promise.all(promises);` and in the next line of code simply do `results.forEach`. – Ronnie Royston Apr 15 '23 at 01:47