EN
TypeScript - async for
12 points
In TypeScript it is possible to create async for
loop in following way.
xxxxxxxxxx
1
interface Iteration<T> {
2
(index : number, entry : T) : void;
3
}
4
5
let iterate = async <T> (array : Array<T>,
6
iteration : Iteration<T>) : Promise<void> => {
7
8
for(let i = 0; i < array.length; ++i)
9
await iteration(i, array[i])
10
};
11
12
/*
13
// This is alternative version of iterate function
14
15
async function iterate<T>(array : Array<T>,
16
iteration : Iteration<T>) : Promise<void> {
17
18
for(let i = 0; i < array.length; ++i)
19
await iteration(i, array[i])
20
}
21
*/
Example:
xxxxxxxxxx
1
let array = new Array<number>();
2
3
for(let i = 0; i < 5; ++i)
4
array.push(2 * i);
5
6
7
iterate(array, (index : number, entry : number) : void => {
8
console.log(`Loop 1: index=${index}, entry=${entry}`);
9
});
10
11
iterate(array, (index : number, entry : number) : void => {
12
console.log(`Loop 2: index=${index}, entry=${entry}`);
13
});
Compiling and running:
xxxxxxxxxx
1
$ tsc --target ES6 Script.ts
2
$ node Script.js
Output:
xxxxxxxxxx
1
Loop 1: index=0, entry=0
2
Loop 2: index=0, entry=0
3
Loop 1: index=1, entry=2
4
Loop 2: index=1, entry=2
5
Loop 1: index=2, entry=4
6
Loop 2: index=2, entry=4
7
Loop 1: index=3, entry=6
8
Loop 2: index=3, entry=6
9
Loop 1: index=4, entry=8
10
Loop 2: index=4, entry=8
Run it online here.
Note: to use
async
/await
--target ES6
parameter is necessary during compilation.