async / await (JavaScript)

async and await let you write asynchronous code that reads like normal step-by-step code. await pauses inside an async function until a promise settles.

JavaScript

Mark a function async to allow await inside it. await waits for a promise to resolve and gives you its value, so you avoid chains of .then().

Wrap awaited calls in try/catch to handle errors, the same way you would with synchronous code.

Syntax

async function name() { const value = await promise; }

Examples

JavaScript

function later(v) {
  return Promise.resolve(v);
}
async function run() {
  const value = await later("ready");
  console.log(value);
}
run();

Output:

ready

Learn it in a lesson

See also

Back to the Dictionary