Getting Started

If you’re using VS Code, it includes TypeScript by default. If you didn’t install TypeScript with VS Code, you can download it here.

You can also install TypeScript using this command:

npm install -g typescript

Let’s create a new folder named typescript . Inside, create a JSON filed named tsconfig.json . This file will be used by the TypeScript compiler to compile our code.

Also, create a new folder named src inside the typescript folder.

Simplify Async Callback Functions using Async/Await

Lets see how we can write a Promise and use it in async await . This method helps simplify the code inside functions like setTimeout .

Create a new file inside src folder called index.ts . We’ll first write a function called start that takes a callback and calls it using the setTimeout function.

const start = callback => {

setTimeout(() => {

callback('Hello');

setTimeout(() => {

callback('And Welcome');

setTimeout(() => {

callback('To Async Await Using TypeScript');

}, 1000);

}, 1000);

}, 1000);

}; start(text => console.log(text));

We can use this function to run a callback that logs some text to the console.

To compile this code, run:

$ tsc src/index.ts

This will create a new file named index.js . You can run this file in the console using node .

$ node src/index.js

You will now notice that the code runs exactly as we want it to. But we can make things much simpler using async await .

All we need to do to use async await is to create a Promise based delay function.

const wait = (ms) => new Promise(res => setTimeout(res, ms));

This function takes a number of milliseconds and returns a Promise that gets resolved using setTimeout after the given number of milliseconds.

Now create an async function called startAsync . This function is actually quite similar to the start function that we had written before. Inside this function, we will use the await to pause the execution of the code until the Promise is resolved and call the callback passing in the time.

const startAsync = async callback => {

await wait(1000);

callback('Hello');

await wait(1000);

callback('And Welcome');

await wait(1000);

callback('To Async Await Using TypeScript');

}; startAsync(text => console.log(text));