Home >Web Front-end >JS Tutorial >How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?

How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 00:16:09379browse

How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?

Waiting for Multiple Asynchronous Tasks to Complete in JavaScript

Problem:

You have a series of asynchronous tasks (promises) and need to execute a block of code only when all of them have been completed.

Solution:

Use Promise.all to collect all promises into a single array and wait for its resolution or rejection.

Implementation:

const promises = [];

for (let i = 0; i < 5; i++) {
  promises.push(doSomeAsyncStuff());
}

Promise.all(promises)
  .then(() => {
    for (let i = 0; i < 5; i++) {
      doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
    }
  })
  .catch((e) => {
    // Handle errors here
  });

Revised doSomeAsyncStuff function:

function doSomeAsyncStuff() {
  return new Promise((resolve, reject) => {
    const editor = generateCKEditor();
    editor.on('instanceReady', (evt) => {
      doSomeStuff();
      resolve(true);
    })
  });
}

Example:

function doSomethingAsync(value) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("Resolving " + value);
      resolve(value);
    }, Math.floor(Math.random() * 1000));
  });
}

function test() {
  const promises = [];

  for (let i = 0; i < 5; i++) {
    promises.push(doSomethingAsync(i));
  }

  Promise.all(promises)
    .then((results) => {
      console.log("All done", results);
    })
    .catch((e) => {
      // Handle errors here
    });
}

test();

The above is the detailed content of How Can I Wait for Multiple JavaScript Promises to Finish Before Continuing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn