Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstration of handling asynchronous functions in loops in typescript using async/await
// Demonstration of different ways of running asynchronous functions in loops
import util = require("util");
const arr = ["a", "b", "c", "d"];
const setTimeoutPromise = util.promisify(setTimeout);
// Asynchronously wait a very short amount of time and then print our value
async function waitAndPrint(s: string): Promise<void> {
await setTimeoutPromise(Math.random() * 100);
console.log(s);
}
// This example uses foreach but doesn't have any means of waiting for the
// functions within the foreach to complete, so "done" appears before the
// results are printed
async function demoForEach(): Promise<void> {
arr.forEach(async a => waitAndPrint("forEach " + a));
// The below - adding "await" - doesn't help as forEach is still
// calling each function asynchronously
// arr.forEach(async a => await waitAndPrint("forEach " + a));
console.log("done");
// We know this doesn't actually "wait" properly, so cheat here to
// avoid polluting the output of the followup functions
await setTimeoutPromise(1000);
}
// Use a map and Promise.all to execute each function simultaneously
// but wait for them all to complete before pritning "done" and returning
async function demoPromiseAll(): Promise<void> {
const promises = arr.map(async a => waitAndPrint("PromiseAll " + a));
await Promise.all(promises);
console.log("done");
}
// Use a basic for loop and embed "await" within the loop to execute
// each function one by one, waiting each time.
async function demoSyncFor(): Promise<void> {
for (const a of arr) {
await waitAndPrint("syncFor " + a);
}
console.log("done");
}
(async () => {
// Comments show example output of each example
// demoForEach
// done
// forEach a
// forEach c
// forEach d
// forEach b
console.log("\ndemoForEach");
await demoForEach();
// demoSyncFor
// syncFor a
// syncFor b
// syncFor c
// syncFor d
// done
console.log("\ndemoSyncFor");
await demoSyncFor();
// demoPromiseAll
// PromiseAll d
// PromiseAll c
// PromiseAll a
// PromiseAll b
// done
console.log("\ndemoPromiseAll");
await demoPromiseAll();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment