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.
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));
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)); }
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!