JS Async/Await
JavaScript async and await: Linear Asynchronous Control Flow
The async and await keywords let you write Promise-based asynchronous code that reads cleanly from top to bottom like synchronous code. Every async function automatically returns a Promise, and await pauses only that function until the awaited Promise settles.
How async / await Runs Without Blocking
flowchart TD
Call["Call async function loadData()"] --> Pause["await pauses loadData(), yields thread to Event Loop"]
Pause --> Ready["Promise settles"]
Ready --> Resume["Resume loadData() in Microtask Queue"]
While one async function pauses at await, the rest of your web page stays interactive because the main thread keeps handling clicks and rendering frames.
Practical fetch() and Parallel Promise.all() Example
Wrap await calls in try...catch to handle network errors, and check response.ok because fetch() does not reject on HTTP 404 or 500 responses. When two async tasks do not depend on each other, start both together with Promise.all() instead of awaiting sequentially.
async function mockFetch(label, delayMs) {
return new Promise((resolve) => {
setTimeout(() => resolve({ label, ok: true }), delayMs);
});
}
async function loadDashboard() {
try {
// Run independent async calls in parallel for faster load times!
const [user, stats] = await Promise.all([
mockFetch("UserProfile", 20),
mockFetch("LessonStats", 25),
]);
console.log("Dashboard ready:", { user, stats });
} catch (err) {
console.error("Dashboard load error:", err.message);
} finally {
console.log("Hide loading spinner.");
}
}
loadDashboard();
Common Mistakes to Avoid
- Awaiting independent requests sequentially: Writing
const a = await getA(); const b = await getB();doubles total waiting time whenbdoes not needa. UsePromise.all([getA(), getB()]). - Ignoring
response.okwithfetch():fetch()resolves normally on HTTP404or500! Always checkif (!res.ok) throw new Error(\HTTP ${res.status}`);before callingres.json()`. - Using
awaitinsideArray.forEach():items.forEach(async item => await save(item))fires everything at once and never waits before continuing. Usefor (const item of items)for sequential work orPromise.all(items.map(...))for parallel work.
Frequently Asked Questions
What does an async function return if you return a plain value like 42?
It automatically wraps that value in a resolved Promise, equivalent to Promise.resolve(42). Callers read it with await fn() or fn().then(...).
Can I use await at the top level of a file without an async function?
Yes, modern ES modules (<script type="module"> and .mjs / ESM Node files) support Top-Level await directly at module scope.
Does try...catch catch rejected Promises if I forget await?
No! If you write return fetchSomething() inside try...catch without await, the function returns the Promise before it rejects, bypassing catch. Always write return await ... inside try...catch.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.