async / await
Write asynchronous code that looks and reads like synchronous code. Discover the modern standard for handling background tasks and the massive performance trap of sequential awaits.
Synchronous Style, Asynchronous Power
Introduced in ES8 (2017), async and await are syntactic sugar built directly on top of Promises.
They allow you to pause a function until a background task finishes, without needing to write any .then() callback chains.
The try / catch Revival
Because async / await makes asynchronous code look synchronous, it brings back a massive feature that Callback Hell destroyed: the standard try / catch block.
You can now wrap a network request in a normal try block and immediately handle any rejection in the catch block, keeping your error handling centralized and readable.
The Two Rules
1. You can only use the await keyword inside a function that is explicitly marked with the async keyword.
2. An async function *always* returns a Promise, even if you just return 5. JavaScript automatically wraps the return value in a resolved Promise.
Sequential vs Parallel Cost
Run two simulated network requests. Notice how sequential await calls stack their loading times, while parallel execution overlaps them.
The Performance Trap
async function loadData() {
const user = await fetchUser();
const posts = await fetchPosts();
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
async / awaitis syntax sugar on top of Promises.- You can only use
awaitinside anasyncfunction (or at the top level of a module). - An
asyncfunction always returns a Promise. awaitpauses the execution of the function until the Promise settles.- Error handling is done using standard
try / catchblocks. - Avoid the sequential trap: don't
awaitindependent tasks one after the other.
Done with this concept?
Mark it complete to track your progress. No login needed.