Home > Web Front-end > JS Tutorial > How to Achieve Asynchronous Chaining in a JavaScript ES6 Promise for Loop?

How to Achieve Asynchronous Chaining in a JavaScript ES6 Promise for Loop?

Barbara Streisand
Release: 2024-11-22 11:52:12
Original
800 people have browsed it

How to Achieve Asynchronous Chaining in a JavaScript ES6 Promise for Loop?

JavaScript ES6 Promise for Loop with Asynchronous Chaining

In the code provided, an attempt is made to create a for loop that iterates 10 times and creates a promise for each iteration. However, the loop executes synchronously, resulting in unpredictable output. The goal is to ensure that each promise runs only after the previous one has resolved.

Promisifying setTimeout

To facilitate the solution, we define a helper function called delay that promisifies the setTimeout function:

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

Creating Asynchronous Promises

To ensure asynchronous execution, we create an initial promise that resolves immediately. Each subsequent promise is chained to the previous one:

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

This approach ensures that each loop iteration creates a promise that resolves after the previous promise has completed. The console.log(i) statement will be executed in the correct order, printing the values from 0 to 9.

The above is the detailed content of How to Achieve Asynchronous Chaining in a JavaScript ES6 Promise 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