Sometimes, we want to write loops for promise with JavaScript.
In this article, we’ll look at how to write loops for promise with JavaScript.
How to write loops for promise with JavaScript?
To write loops for promise with JavaScript, we can use the for-of loop with async and await.
For instance, we write
const sayHi = () => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Hi");
resolve();
}, 3000);
});
};
const asyncArray = [sayHi, sayHi, sayHi];
const hi = async () => {
for (const func of asyncArray) {
console.log(await func());
}
};
to define the sayHi function that returns a promise.
Then we define the asyncArray array with references to sayHi.
Next, we have the hi function that loops through the functions in asyncArray and call them in the for-of loop.
We use await to get the resolve value of each promise.
Conclusion
To write loops for promise with JavaScript, we can use the for-of loop with async and await.