async await in a loop code example
Example 1: async for loop
(async function loop() {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
console.log(i);
}
})();
Example 2: foreach async typescript
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
Example 3: async await in forloops
// Series loop
async (items) => {
for (let i = 0; i < items.length; i++) {
// for loop will wait for promise to resolve
const result = await db.get(items[i]);
console.log(result);
}
}
// Parallel loop
async (items) => {
let promises = [];
// all promises will be added to array in order
for (let i = 0; i < items.length; i++) {
promises.push(db.get(items[i]));
}
// Promise.all will await all promises in the array to resolve
// then it will itself resolve to an array of the results.
// results will be in order of the Promises passed,
// regardless of completion order
const results = await Promise.all(promises);
console.log(results);
}
Example 4: async foreach
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
asyncForEach([1, 2, 3], async (num) => {
await waitFor(50);
console.log(num);
})