Home > Web Front-end > JS Tutorial > How to Achieve Asynchronous Chaining with Promises in JavaScript?

How to Achieve Asynchronous Chaining with Promises in JavaScript?

Susan Sarandon
Release: 2024-12-04 20:11:16
Original
729 people have browsed it

How to Achieve Asynchronous Chaining with Promises in JavaScript?

Asynchronous Chaining with Promises in JavaScript ES6

The JavaScript code snippet provided attempts to create promises within a loop, but fails due to the synchronous nature of the loop. To address this, we require each promise to be created and resolved sequentially, resulting in an asynchronous.

There are several approaches to achieve this chaining:

Using a For Loop with an Initial Promise:

Initialise a promise that immediately resolves, then chain new promises to this initial one as each previous promise resolves.

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

for (let i = 0, p = Promise.resolve(); i < 10; i++) {
    p = p.then(() => delay(Math.random() * 1000))
         .then(() => console.log(i));
}
Copy after login

Using Array.reduce with an Initial Promise:

Similar to the for loop approach, use Array.reduce to chain promises, starting with an initial promise.

[...Array(10).keys()].reduce(
    (p, i) => p.then(() => delay(Math.random() * 1000)).then(() => console.log(i)),
    Promise.resolve()
);
Copy after login

Using a Recursively Chaining Function:

Define a function that calls itself as a resolution callback (like a promise chain), passing the current index as an argument.

const chainPromises = (i = 0) => {
    if (i >= 10) return;

    delay(Math.random() * 1000).then(() => {
        console.log(i);
        chainPromises(i + 1);
    });
};

chainPromises();
Copy after login

Using Async/Await (ES2017):

Use async/await to pause the execution of the function until the promise resolves.

const asyncPromises = async () => {
    for (let i = 0; i < 10; i++) {
        await delay(Math.random() * 1000);
        console.log(i);
    }
};

asyncPromises();
Copy after login

Using For Await...Of (ES2020):

Similar to async/await, use the for await...of syntax to iterate over an async iterable.

const asyncPromises = async () => {
    for await (let i of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) {
        await delay(Math.random() * 1000);
        console.log(i);
    }
};

asyncPromises();
Copy after login

The above is the detailed content of How to Achieve Asynchronous Chaining with Promises in JavaScript?. 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