Home >Web Front-end >JS Tutorial >How Can I Sequentially Execute Promises in a JavaScript ES6 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()).
To improve our code, let's create a promisified version of setTimeout:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
This function returns a promise that resolves when the timer expires, allowing us to easily chain promises.
With a promisified setTimeout, several methods exist to implement the desired chaining:
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)); }
Another option is to use Array.reduce:
[...Array(10)].reduce((p, _, i) => p.then(() => delay(Math.random() * 1000)) .then(() => console.log(i)), Promise.resolve());
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());
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();
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); }
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!