Skip to content

Async / Await

The async keyword before a function declaration makes it an async function. Async functions always return a Promise — even if you return a plain value, it is automatically wrapped in Promise.resolve(value).

async function greet() {
return 'hello';
}
greet().then(function(v) { console.log(v); }); // hello

Inside an async function, await pauses execution until the Promise settles, then resumes with the resolved value. The rest of the program keeps running while awaiting.

async function loadUser() {
var user = await fetchUser(42); // pauses here until fetchUser resolves
var posts = await fetchPosts(user.id);
return posts;
}

Wrap await expressions in try/catch to handle rejections:

async function run() {
try {
var data = await fetchData();
console.log(data);
} catch (err) {
console.error('Failed:', err.message);
}
}

Two sequential await calls run one after the other — the second starts only after the first completes:

var a = await fetchA(); // waits
var b = await fetchB(); // then waits again

To run both concurrently, start the Promises first and await them together:

var [a, b] = await Promise.all([fetchA(), fetchB()]);

The snippet below uses a fakeFetch helper (setTimeout-based) to simulate async calls. It first fetches sequentially, then fetches both in parallel with Promise.all.

JavaScript

Output: Sequential: A then B, then Parallel: A and B.

What does an async function always return?
What is the correct way to handle a rejection from an awaited Promise?
Which pattern runs two async operations concurrently rather than sequentially?