Home > Article > Web Front-end > How to Serialize Promises in a JavaScript ES6 For Loop?
JavaScript ES6 Promise For Loop Serialization
In the given code, you attempt to execute promises sequentially within a for loop but encounter a problem where the loop executes synchronously, resulting in unpredictable output.
Understanding the Issue:
A promise encapsulates an asynchronous operation, but the loop's synchronous nature triggers all promises simultaneously, disregarding the desired sequence.
Promisifying setTimeout:
To facilitate the sequential execution, we can promisify setTimeout to obtain a promise that resolves when the timer expires:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
Solution Options:
There are multiple ways to solve this problem, leveraging promises and asynchronous programming techniques.
1. For Loop with Initial Promise:
By starting with an immediately resolving promise, you can chain subsequent promises as the previous ones resolve:
for (let i = 0, p = Promise.resolve(); i < 10; i++) { p = p .then(() => delay(Math.random() * 1000)) .then(() => console.log(i)); }
2. Array.reduce with Initial Promise:
Using Array.reduce, you can create a chain of promises similar to the for loop approach:
[...Array(10)] .reduce( (p, _, i) => p.then(() => delay(Math.random() * 1000)) .then(() => console.log(i)), Promise.resolve() );
3. Function as Promise Resolution Callback:
You can define a function that passes itself as the resolution callback, allowing for a recursive promise chain:
const loop = (i) => { delay(Math.random() * 1000) .then(() => console.log(i)) .then(() => { if (i < 10) loop(i + 1); }); }; loop(0);
4. async/await Syntax (ES2017):
ES2017 introduced async/await syntax to simplify asynchronous code handling:
const main = async () => { for (let i = 0; i < 10; i++) { await delay(Math.random() * 1000); console.log(i); } }; main();
5. for await...of Syntax (ES2020):
ES2020 introduced a special syntax for iterating over async iterables:
(async () => { for await (const i of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) { await delay(Math.random() * 1000); console.log(i); } })();
By utilizing these techniques, you can execute promises sequentially within a loop, ensuring the desired ordering of operations and avoiding unpredictable output.
The above is the detailed content of How to Serialize Promises in a JavaScript ES6 For Loop?. For more information, please follow other related articles on the PHP Chinese website!