Async Await In JS

Async Await In JS

·

2 min read

  • The async and await keywords in JS that lets us make the functions asynchronous and enable asynchronous, promise-based behavior to be written in a cleaner style .

what does the async keyword do:

  • If we add Async keyword before any function then that functions becomes asynchronous function and it returns a Promise .

what does the await keyword do:

  • talking in terms of output that we see -> blocks the code execution untill the await expession gets resolved i.e ==> returning promise is settled==>now next line would be executed only when await line will get it's promise resolved.
  • talking in terms of how code works behind the hood : so async and await never blocks code execution but instead they wrap all code in async function inside big Promise and then the then() method would be called asynchronously.
  • Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected.
  • The resolved value of the promise is treated as the return value of the await expression.

Error handling in Async Await-

  • we use normal Try catch block instead of then().catch() chain.
  • the flow in try catch would be if one of the promise gets rejected then thr succeeding try would be skipped and code in catch block will be executed.