Tuesday, March 26, 2019

From Promise to async/awiat in Typescript Part I

Diving in the asynchronous programming environment for a long while, at least 3 or 4 years I think, from Promise to Rx Observables. Until recently I finally found that they actually put this pattern support explicitly into ES6(ECMAScript 2015) implementation.




In ES6 we can now write native Promises without importing 3rd-party libraries, such as Q or async, which are needed in javascript in early versions.
They haven't include supports for Rx Observables yet but so far they are still working on it.

Later in ECMAScript 2017, the javascript geniuses introduced async/await keywords for code readability. They are coupled to represent asynchronous process flow in code. Let's see a simple demo code.

async doSomething() {
  console.log('I am a coward !');
}

async function asyncCall() {
  console.log('Calling');
  await doSomething();
  console.log('Hang up');
}

asyncCall();
console.log('Kelly I think I\'m still missing you');

The console output will be...
Kelly I think I'm still missing you
Calling
I am a coward !
Hang up


Now, the async keyword is actually another way to say "This function always runs asynchronously and returns Promise". So when we call it, it will start running in background without blocking the caller. And in typescript, the function declaration is the same as this one:

function asyncCall(): Promise<void>

The await keyword stands for "Dude, stop here. you have to wait for this little async finishing her job". That means the execution of asyncCall() will stop at doSomething(), wait for it returns, then run the rest code of asyncCall().

Here if we remove await before doSomething(), then the order of output will be:
...
Hang up
I'm a coward !







No comments:

Post a Comment