Here is a good example of the code to call async function in loop for element of an array and update the exiting array. In this example I have used the Array.prototype.entries() function to get the index and value of each array item of a simple array. Array.prototype.entries() method helps to iterate an array with index and element.
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function resolveAfter2Seconds(num) {
await timeout(2000);
return num;
}
async function main() {
let arr = ["Saab", "Volvo", "BMW"];
for (let [index, val] of arr.entries()) {
console.log(index, val);
console.log(await resolveAfter2Seconds(val));
}
}
main();
Comments