JavaScript Async

Javascript has come a long way from callbacks to promises, and ever since then, asynchronous javascript is even convenient with async/await syntax. Async functions are combos of both promises and generators.

Async functions are high-level abstraction over-promises, and async/await is built on promises. To avoid the need to configure promise chains explicitly, async functions are used.

An async function is declared with the async keyword and await permitted within it. Async and await both keywords enable asynchronous promise-based behavior.

Syntax:

async function name([param[, param[, ...param]]]) {
   statements
}

Name: Function's Name
Param: The argument's name must be passed to the function.
Statement: The statement comprising the body of the function. Await might be used.

async function myFunction() {
  return "Hi";
}

and 

function myFunction() {
  return Promise.resolve("Hi");
}
  • They are both the same and return the same outcome. The motive is that using async before a function makes the function return a promise.

Example:

We will see how async can work with promise.

function missionStatus() {
    return new Promise(mission => {
      setTimeout(() => {
        mission('Mission Passed Respect++');
      }, 3000);
    });
  }
  
  async function asyncCall() {
    console.log('Checking...');
    const result = await missionStatus();
    console.log(result);
  }
  
  asyncCall();
  • The function missionStatus has the promise with the argument "mission."
  • The timeout is set to 3000ms with a custom message to display after 3000ms.
  • The following async function, asyncCall, is created with a console log message.
  • Await is declared with async so that it makes promise returning functions behave as though they are synchronous by suspending execution until the promise is fulfilled or rejected.
  • The resolved promise is treated as the return value after then.

  • So after 3000ms, asyncCall returns the resolved promise message.
Wed, 07/13/2022 - 10:25

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags