Async Await

ASYNC

The async keyword is used to write functions that handle asynchronous actions. We wrap our asynchronous logic inside a function prepended with the async keyword.

async function myFunc() {
  // Function body here
};
 
myFunc();
  • If there’s nothing returned from the function, it will return a promise with a resolved value of undefined.

  • If there’s a non-promise value returned from the function, it will return a promise resolved to that value.

  • If a promise is returned from the function, it will simply return that promise

async function fivePromise() { 
  return 5;
}
 
fivePromise()
.then(resolvedValue => {
    console.log(resolvedValue);
  })  // Prints 5

AWAIT

operator used inside an async function that halts the execution of a function until a given promise is no longer pending and returns the resolved value of the promise.

Review

  • async...await is syntactic sugar built on native JavaScript promises and generators.

  • We declare an async function with the keyword async.

  • Inside an async function we use the await operator to pause execution of our function until an asynchronous action completes and the awaited promise is no longer pending .

  • await returns the resolved value of the awaited promise.

  • We can write multiple await statements to produce code that reads like synchronous code.

  • We use try...catch statements within our async functions for error handling.

  • We should still take advantage of concurrency by writing async functions that allow asynchronous actions to happen in concurrently whenever possible.

The await keyword can only be used inside an async function. await is an operator: it returns the resolved value of a promise. Since promises resolve in an indeterminate amount of time, await halts, or pauses, the execution of our async function until a given promise is resolved.

Comparison of ASYNC and normal syntax

Explanation :

  • We mark our function as async.

  • Inside our function, we create a variable firstValue assigned await returnsFirstPromise(). This means firstValue is assigned the resolved value of the awaited promise.

  • Next, we log firstValue to the console.

  • Then, we create a variable secondValue assigned to await returnsSecondPromise(firstValue). Therefore, secondValue is assigned this promise’s resolved value.

  • Finally, we log secondValue to the console.

Though using the async...await syntax can save us some typing, the length reduction isn’t the main point. Given the two versions of the function, the async...await version more closely resembles synchronous code, which helps developers maintain and debug their code. The async...await syntax also makes it easy to store and refer to resolved values from promises further back in our chain which is a much more difficult task with native promise syntax.

try & catch for error handling

Handling Independent Promises

Last updated