Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

async function

A function that always returns a promise and lets you use await inside.

Available since: ES2017

Syntax

async function name() { … } / async () => { … }

Examples

An async function returns a promise:

async function getNumber() {
  return 42;
}
 
console.log(getNumber() instanceof Promise);
console.log(await getNumber());

Output:

true
42

Sequential steps with error handling:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
 
const loadUser = async (id) => {
  await wait(50);
  if (id < 0) throw new Error('Bad id');
  return { id, name: 'Anna' };
};
 
try {
  const user = await loadUser(1);
  console.log(user.name);
  await loadUser(-1);
} catch (error) {
  console.log(error.message);
}

Output:

Anna
Bad id

Notes

A throw inside an async function becomes a rejected promise and return a fulfilled one. Arrow functions and methods can be async too.

See also

  • await — Waits for a promise and returns its value.
  • Promise — A promise of a result that will be ready later: success or failure.
  • try...catch — Catches errors so the program does not stop.

Related recipes

In the tutorial

  • async and await — Asynchronous functions in JavaScript: async, await, error handling with try...catch, sequential and parallel waiting.

Thanks for reading!

Donate to the site — we work hard for you.