In the post Asynchronous Programming with Async and Await, I compaired asyncchronous programming in C#, ES7(ES2016) and TypeScript. It surprises me that TypeScript has already implemented async and await and has a fully support. Here I’m going to talk a little bit more about how to use Template with Promise so as to support return type of await result.

For example, here’s last snippet:

1
2
3
4
5
6
7
8
9
10
11
12
async function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function ping(someone) {
for (var i = 0; i < 5; i++) {
await delay(1000);
console.log("ping " + someone);
}
}

ping('zp_j');

How to support return value with defined type for the method deplay()? Here’s the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function delay(ms: number) {
return new Promise<number[]>(
resolve => setTimeout(
() => resolve([0, 1, 2]), ms
)
);
}

async function ping(someone: string) {
for (var i = 0; i < 5; i++) {
let result: number[] = await delay(1000);
console.log("ping " + someone + " with return value: " + JSON.stringify(result));
}
}

ping('zp_j');

Here we add the return type to Promise, because Promise use a template as the return type. When we call delay() the return type is set to be number[].