Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

TypeScript - async for

0 contributions
12 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more