Home >Web Front-end >JS Tutorial >How to Use Promise.all to Manage and Await Multiple Promises?

How to Use Promise.all to Manage and Await Multiple Promises?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 17:37:11569browse

How to Use Promise.all to Manage and Await Multiple Promises?

How to Handle Multiple Promises and Await Their Completion

When working with asynchronous code, it's often necessary to handle multiple promises and wait for them all to complete before proceeding. This article will guide you through achieving this using Promise.all.

Introducing Promise.all

Promise.all accepts an array of promises and returns a single promise that resolves when all the input promises have resolved, or rejects if any one of them rejects.

Restructuring doSomeAsyncStuff to Return a Promise

To make doSomeAsyncStuff work with promises, modify it as follows:

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

Using Promise.all to Wait for All Async Tasks

Once doSomeAsyncStuff returns a promise, you can use Promise.all to wait for all instances of it to complete. Here's an improved version of your code:

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
    });

This code creates an array of promises from each call to doSomeAsyncStuff. Promise.all takes this array and waits for all the promises to resolve. Once all promises are resolved, the then callback is executed, allowing you to perform actions that depend on the results of the asynchronous tasks.

The above is the detailed content of How to Use Promise.all to Manage and Await Multiple Promises?. 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