Async for loop JavaScript 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: async await in forloops
async (items) => {
for (let i = 0; i < items.length; i++) {
const result = await db.get(items[i]);
console.log(result);
}
}
async (items) => {
let promises = [];
for (let i = 0; i < items.length; i++) {
promises.push(db.get(items[i]));
}
const results = await Promise.all(promises);
console.log(results);
}
Example 3: wait for loop to finish javascript
async function processArray(array) {
const promises = array.map(delayedLog);
await Promise.all(promises);
console.log('Done!');
}
Example 4: C# foreach loop async but wait at end
public async Task RunAsync()
{
var tasks = new List<Task>();
foreach (var x in new[] { 1, 2, 3 })
{
var task = DoSomethingAsync(x);
tasks.Add(task);
}
await Task.WhenAll();
}
Example 5: loop async javascript
const mapLoop = async _ => {
console.log('Start')
const numFruits = await fruitsToGet.map(async fruit => {
const numFruit = await getNumFruit(fruit)
return numFruit
})
console.log(numFruits)
console.log('End')
}
Example 6: loop async javascript
const forEachLoop = _ => {
console.log('Start')
fruitsToGet.forEach(async fruit => {
const numFruit = await getNumFruit(fruit)
console.log(numFruit)
})
console.log('End')
}