Callback, Promise, Async, and Await in TypeScript

I'm going to expand the explanation of JS Async from W3Schools by giving a simple example in TypeScript. I'm going to convert callbacks to promise/async/await functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const c = (f: Function) => {
  setTimeout(() => {
    f('Callback 1');
    setTimeout(() => {
      f('Callback 2');
      setTimeout(() => {
        f('Callback 3');
      }, 1000);
    }, 1000);
  }, 1000);
};

c((text: string) => console.log(text));

The setTimeout has three parameters; function, milliseconds, and infinity arguments. In a function parameter, we printed Callback n and executed the setTimeout again. We created three-level nested functions. Every level has a delay of 1000 milliseconds or 1 second.

We can try to execute the code above in our local and see the result. The Callback 1 appeared then waited one second then Callback 2 appeared then waited for another second for Callback 3.

Maybe you think that nested callbacks are ugly because it has many levels. We can break it by using promise/async/await functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const delay = (ms: number) => new Promise(f => setTimeout(f, ms));
const p = async (f: Function) => {
  await delay(1000);
  f('Promise 1');
  await delay(1000);
  f('Promise 2');
  await delay(1000);
  f('Promise 3');
};

p((text: string) => console.log(text));

We created a Promise function called delay that has a setTimeout inside. We put await in front of delay and make the p function an async function. The await only works in async functions. The delay function can work with await syntax because of the Promise.

It produced the same intuition as the callbacks above. Try to remove the async and await syntaxes and you will see it prints responses at the same time.

Callback, await, and async are mostly used to fetch data from REST APIs. They are used when it is necessary to wait for the result of functions. I used the setTimeout to make a delay because I thought it was a good example of replicating those conditions. You can get these examples at https://github.com/aristorinjuang/ts-async.

Related Articles