async function

Declares an asynchronous function that always returns a promise and can use the await keyword inside it.

Returns
A promise (Promise) that fulfills with the value from return, or is rejected with the thrown error.
On this page

Example

#
JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

async function loadProfile(name) {
  await wait(300)
  return { name, level: 7 }
}

const promise = loadProfile('Emma')
console.log(promise)

const profile = await promise
console.log(profile)
Console
Promise { <pending> }
{ name: 'Emma', level: 7 }

Definition and usage

#

The async keyword before a function turns it into an asynchronous function. Such a function always returns a promise: the value from return becomes the value of the fulfilled promise, and a thrown exception causes it to be rejected.

Inside an async function you can use await to wait for another promise’s result. The code then looks like ordinary, top-to-bottom code, and you catch errors with the familiar try...catch block instead of the catch() method.

async works with every form of function: a declaration, an expression, an arrow function (async () => {}), and a method on an object or class. Calling an async function doesn’t block the program. Code written after the call runs immediately, before the function finishes its work.

Syntax

#
Syntax
async function name(param1, param2) {
  …
}

const name = async (param) => {
  …
}

More examples

#
A thrown exception rejects the promise
JavaScript
async function buyCourse(price, balance) {
  if (balance < price) throw new Error('Not enough coins')
  return balance - price
}

buyCourse(50, 80).then((rest) => console.log('Left:', rest))
buyCourse(90, 80).catch((error) => console.log('Error:', error.message))
Console
Left: 30
Error: Not enough coins
An arrow function and a method
JavaScript
const getPoints = async () => 120

const shop = {
  async buy(item) {
    const points = await getPoints()
    return `${item}: ${points - 100} points left`
  }
}

console.log(await shop.buy('New avatar'))
Console
New avatar: 20 points left

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Simply calling an async function gives you a Promise object. To get the result, use await or then().
  • Don’t mark a function as async if it doesn’t do anything asynchronous. You’d needlessly turn its result into a promise.
  • Handle an async function’s errors with try...catch inside it, or with catch() at the call site.

Related entries

#

Spotted a mistake or missing an example? Write to us.