Languages
[Edit]
EN

TypeScript - async for

12 points
Created by:
Root-ssh
174740

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join