The JavaScript async function statement
An async function always returns a promise and lets you use await inside it to pause for asynchronous results. async function load() { const res = await fetch(url); }. It makes asynchronous code read like ordinary top-to-bottom code, and pairs with try...catch for errors.
Overview
An async function is the modern way to write asynchronous code that reads clearly. Mark a function async and you can use await inside it to pause until a promise settles, then continue with the result — no nested callbacks, no long .then() chains. const data = await fetch(url).then(r => r.json()) becomes two plain lines.
Two facts define how it behaves. An async function always returns a promise, even if you return a plain value (it gets wrapped). And await can only be used inside an async function (or at the top level of a module) — try it in a regular function and you get a syntax error. So the usual shape is: an outer async function containing your awaited calls.
Error handling is a highlight. Because a rejected promise throws at the await, you handle failures with a normal try...catch — far nicer than .catch() callbacks. The arrow form works too: const load = async () => { ... }. To run several independent async operations at once rather than one after another, await Promise.all([...]) is the tool.
Syntax
async function load() {
const res = await fetch("/api");
const data = await res.json();
return data; // resolves the returned promise
}
// arrow form
const load = async () => { /* ... */ };
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
// a promise that resolves after a short delay
const wait = ms => new Promise(r => setTimeout(r, ms));
async function run() {
document.getElementById('out').textContent = 'Loading...';
await wait(800);
document.getElementById('out').textContent = 'Done after awaiting!';
}
run();
</script>
Best practices
- Use try...catch around await calls to handle rejected promises.
- Remember an async function always returns a promise — call it with
awaitor.then(). - Run independent async work in parallel with
await Promise.all([...])instead of sequential awaits. - Don't forget the
await— calling an async function without it gives you a pending promise, not the value.
Frequently asked questions
What does an async function return?
Why can't I use await outside an async function?
async function (or at the top level of a module). Elsewhere it's a syntax error.How do I handle errors in an async function?
How do I run multiple async operations at once?
await Promise.all([p1, p2]) to await several promises in parallel rather than one at a time.