Wednesday, January 25, 2017

How to make an async function synchronous in Typescript? – async-await

Async-await is a way to tell the JavaScript runtime to pause the executing of code on the await keyword when used on a promise and resume only once (and if) the promise returned from the function is settled.
e.g.
function delay(ms: number) {   return new Promise<void>(function(resolve) {     setTimeout(resolve, ms);   }); } --------------------
async function asyncAwait() {   console.log("Knock, knock!");   await delay(1000);   console.log("Who's there?");   await delay(1000);   console.log("async/await!"); }
--------------------
In this example delay is a function which returns
instance of Promise after ms milliseconds.
So when we are using it in our function asyncAwait(), due to await keyword it pause the execution of code and resume only once it complete its process after ms milliseconds. Then next statement will be called. So the output of function calling is given below.
Output:
 asyncAwait();
// [After 0s] Knock, knock!
// [After 1s] Who's there?
// [After 2s] async/await!
--------------------
When the promise settles execution continues,
·         if it was fulfilled then await will return the value,
·         if it's rejected an error will be thrown synchronously which we can catch.

This suddenly (and magically) makes asynchronous programming as easy as synchronous programming. Three things are needed for this though experiment are.
·         Ability to pause function execution.
·         Ability to put a value inside the function.
·         Ability to throw an exception inside the function.


No comments:

Post a Comment