Skip to content

Instantly share code, notes, and snippets.

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);
// 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));
// 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 = a => waitAndPrint("PromiseAll " + a));
await Promise.all(promises);
// 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);
(async () => {
// Comments show example output of each example
// demoForEach
// done
// forEach a
// forEach c
// forEach d
// forEach b
await demoForEach();
// demoSyncFor
// syncFor a
// syncFor b
// syncFor c
// syncFor d
// done
await demoSyncFor();
// demoPromiseAll
// PromiseAll d
// PromiseAll c
// PromiseAll a
// PromiseAll b
// done
await demoPromiseAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment