await foreach javascript then return code example
Example 1: foreach async typescript
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
Example 2: 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);
})
Example 3: 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();
}