Asynchronous Chaining with Promises in JavaScript ES6
The JavaScript code snippet provided attempts to create promises within a loop, but fails due to the synchronous nature of the loop. To address this, we require each promise to be created and resolved sequentially, resulting in an asynchronous.
There are several approaches to achieve this chaining:
Using a For Loop with an Initial Promise:
Initialise a promise that immediately resolves, then chain new promises to this initial one as each previous promise resolves.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); for (let i = 0, p = Promise.resolve(); i < 10; i++) { p = p.then(() => delay(Math.random() * 1000)) .then(() => console.log(i)); }
Using Array.reduce with an Initial Promise:
Similar to the for loop approach, use Array.reduce to chain promises, starting with an initial promise.
[...Array(10).keys()].reduce( (p, i) => p.then(() => delay(Math.random() * 1000)).then(() => console.log(i)), Promise.resolve() );
Using a Recursively Chaining Function:
Define a function that calls itself as a resolution callback (like a promise chain), passing the current index as an argument.
const chainPromises = (i = 0) => { if (i >= 10) return; delay(Math.random() * 1000).then(() => { console.log(i); chainPromises(i + 1); }); }; chainPromises();
Using Async/Await (ES2017):
Use async/await to pause the execution of the function until the promise resolves.
const asyncPromises = async () => { for (let i = 0; i < 10; i++) { await delay(Math.random() * 1000); console.log(i); } }; asyncPromises();
Using For Await...Of (ES2020):
Similar to async/await, use the for await...of syntax to iterate over an async iterable.
const asyncPromises = async () => { for await (let i of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) { await delay(Math.random() * 1000); console.log(i); } }; asyncPromises();
The above is the detailed content of How to Achieve Asynchronous Chaining with Promises in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!