Asynchronous functions – async and await

Asynchronous functions are a TypeScript feature that arrived with the TypeScript 1.6 release. Developers can use the await keyword to wait for the function results without blocking the normal execution of the program.

Using asynchronous functions helps to increase the readability of a piece of code when compared with the use of promises or callbacks, but technically, we can achieve the same features using both promises and synchronous code.

Let's take a look at a basic async/await example:

let p = Promise.resolve(3); 
 
async function fn(): Promise<number> { 
    let i = await p; // 3 
    return 1 + i; // 4 
} 
 
fn().then((r) => console.log(r)); // 4 

The preceding code snippet declares a promise named p. This promise ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.