Languages
[Edit]
EN

TypeScript - async for

12 points
Created by:
Root-ssh
6322

In TypeScript it is possible to create async for loop in following way.

1. Async for example

interface Iteration<T> {
    (index : number, entry : T) : void;
}

let iterate = async <T> (array : Array<T>, 
    iteration : Iteration<T>) : Promise<void> => {

    for(let i = 0; i < array.length; ++i)
        await iteration(i, array[i])
};

/*
// This is alternative version of iterate function

async function iterate<T>(array : Array<T>,
    iteration : Iteration<T>) : Promise<void> {

    for(let i = 0; i < array.length; ++i)
        await iteration(i, array[i])
}
*/

Example:

let array = new Array<number>();

for(let i = 0; i < 5; ++i)
    array.push(2 * i);


iterate(array, (index : number, entry : number) : void => {
    console.log(`Loop 1: index=${index}, entry=${entry}`);
});

iterate(array, (index : number, entry : number) : void => {
    console.log(`Loop 2: index=${index}, entry=${entry}`);
});

Compiling and running:

$ tsc --target ES6 Script.ts
$ node Script.js

Output:

Loop 1: index=0, entry=0
Loop 2: index=0, entry=0
Loop 1: index=1, entry=2
Loop 2: index=1, entry=2
Loop 1: index=2, entry=4
Loop 2: index=2, entry=4
Loop 1: index=3, entry=6
Loop 2: index=3, entry=6
Loop 1: index=4, entry=8
Loop 2: index=4, entry=8

Run it online here. 

Note: to use async / await --target ES6 parameter is necessary during compilation.

See also

  1. TypeScript - how to compile ts file to js

References

  1. async / await - Microsoft Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.