Home > Web Front-end > JS Tutorial > How to Pause Execution Until Multiple Promises Resolve?

How to Pause Execution Until Multiple Promises Resolve?

Patricia Arquette
Release: 2024-12-27 03:02:13
Original
531 people have browsed it

How to Pause Execution Until Multiple Promises Resolve?

Return Multiple Promises and Pause Execution Until All Completed

You need to handle multiple asynchronous operations with a method that returns promises. After these operations complete, you want to execute another set of code only when all promises have resolved.

Promises in doSomeAsyncStuff()

Your doSomeAsyncStuff() function needs to return a Promise. This promise reflects the completion of the asynchronous task:

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

Using Promise.all()

Once your asynchronous function returns a Promise, you can use Promise.all() to aggregate these promises into a single Promise:

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((error) => {
        // Handle errors here
    });
Copy after login

Example

Below is an example that logs a message after all five asynchronous tasks have finished:

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((error) => {
            // Handle errors here
        });
}

test();
Copy after login

The above is the detailed content of How to Pause Execution Until Multiple Promises Resolve?. 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