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.
|
|
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.
|
|
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
- TypeScript with MySQL
- Simple REST API with TypeScript
- TypeScript Crash Course
- React with TypeScript
- jQuery Semantic Tabs