ScanSkill

async function

An async function is a function, that is asynchronous while operating. While calling the function a promise is returned, so while calling the asynchronous function the promise has to be resolved to get the actual data.

Syntax

async function name(param, ...) {
  // Statements
}

The async function statement is used to group code into blocks of codes like functions, it may take in parameters, and it may return something back. The difference is in its working mechanism, it works on the javascript promises.

Example

async function items() {
  return ['apple', 'phone', 'laptop', 'dog'];
}

async function printItems() {
  console.log(items()); // Prints: Promise { [ 'apple', 'phone', 'laptop', 'dog' ] }

  const randomItems = await items();
  for(let item of randomItems) {
    console.log(item);
  }
}

printItems();
/* Prints:
apple
phone
laptop
dog
*/

To get the return value from the async function we need to await, which awaits for the value returned by the function and resolves the promise. await statements can only be used inside async functions.