Async / Await
async functions
Section titled “async functions”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); }); // helloInside 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;}Error handling
Section titled “Error handling”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); }}Sequential vs concurrent
Section titled “Sequential vs concurrent”Two sequential await calls run one after the other — the second starts only after the first completes:
var a = await fetchA(); // waitsvar b = await fetchB(); // then waits againTo run both concurrently, start the Promises first and await them together:
var [a, b] = await Promise.all([fetchA(), fetchB()]);Runnable demo
Section titled “Runnable demo”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.
Output: Sequential: A then B, then Parallel: A and B.