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
Release: 2024-12-19 00:16:09
Original
391 people have browsed it

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
  });
Copy after login

Revised doSomeAsyncStuff function:

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

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template