Home > Web Front-end > JS Tutorial > How Can I Sequentially Execute Promises in a JavaScript ES6 For Loop?

How Can I Sequentially Execute Promises in a JavaScript ES6 For Loop?

Patricia Arquette
Release: 2024-12-03 17:11:10
Original
932 people have browsed it

How Can I Sequentially Execute Promises in a JavaScript ES6 For Loop?

JavaScript ES6 Promise for Loop

In programming, a common task is to iterate through a collection and perform asynchronous operations on each element. In JavaScript ES6, promises offer a powerful means to achieve this. However, ensuring that each promise executes only after the preceding one can be challenging.

In the provided code snippet, the for loop creates all promises synchronously, resulting in random output. Our goal is to make each promise run sequentially (.then()).

Promisifying setTimeout

To improve our code, let's create a promisified version of setTimeout:

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

This function returns a promise that resolves when the timer expires, allowing us to easily chain promises.

Chaining Promises

With a promisified setTimeout, several methods exist to implement the desired chaining:

1. With for

Using a for loop, create an initial immediately resolving promise and chain new promises as previous ones resolve:

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

2. With Array.reduce

Another option is to use Array.reduce:

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

3. With Recursive Function

A recursive function can be employed as well:

const loopPromise = (i, p) => {
    if (i >= 10) {
        return;
    }
    p.then(() => delay(Math.random() * 1000))
     .then(() => console.log(i))
     .then(() => loopPromise(i + 1, p));
};

loopPromise(0, Promise.resolve());
Copy after login

4. With Async / Await

This syntax is available in ECMAScript 2017:

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

asyncLoop();
Copy after login

5. With for await...of

Introduced in ECMAScript 2020, this syntax furthers simplifies the loop:

for await (let i of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) {
    await delay(Math.random() * 1000);
    console.log(i);
}
Copy after login

By leveraging these methods, we can effectively chain promises in a for loop, ensuring that each promise executes only after its predecessor resolves.

The above is the detailed content of How Can I Sequentially Execute Promises in a JavaScript ES6 For Loop?. 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