Friday, 25 September 2020

Async Await in TypeScript

TypeScript 1.7 now supports async await keywords for asynchronous programming. This makes the codes more readable and simpler than using the older syntax.
If we have this before:
getItems() {
 return new Promise((resolve, reject) => {
   . . .
   resolve(items);
 });
};
Now can be written as:
async getItems() {
 . . .
 // return items; // this will automatically wrap with Promise type
 return Promise.resolve(items);
}
An async function always return Promise type. If there is an object to be returned and not explicitly written with Promise, it will wrap the object.

To run async method synchronously or to wait until it finishes, we use await keywords.
// previous way
getItems()
 .then((items) => {
    print(items);
     . . .
 });
 
// new way
let items = await getItems();
print(items);
Similarly if we would like to run a number of async methods synchronously, like how we used to do that with a chain of .then( . . .), now we do:
let resultOne = await functionOne();
let resultTwo = await functionTwo(resultOne);
let resultThree = await functionThree(resultTwo);

// or if the functions do not return anything
await functionOne();
await functionTwo();
await functionThree();

To handle error, now we use try catch.
getItems() {
   try {
      . . .
      return Promise.resolve(items);
   }
   catch(error) {
      . . .
      return Promise.reject(error_message);
   }
 });
};
Then when we call the function, the returned Promise.reject() will be treated as an error:
try {
   . . .
   getItems();
}
catch(error_message) {
   print(error_message);
}

To run a bunch of async functions without any particular order we use Promise.all():
Promise.all([functionOne(), functionTwo(), functionThree()]);
Promise.all() returns a Promise that has an array of resolved values from each function.

Finally, Promise.race() is used to run a bunch of async functions and return the first one resolves or rejects. It will return a new Promise with the value of the first function finishes.


Further reading:
Keep Your Promises in TypeScript using async/await