All 28 lessons ▾
Inside JavaScript · Lesson 23 of 28
async/await Part 1: What await Really Pauses
So await looks like it stops JavaScript and waits. It doesn't! So today, let's see exactly what await pauses, and what keeps running behind it.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- async functions always return a promise
- await gives you a promise's value
- await only works inside async functions
- Promises run side by side; await waits in order
- await suspends the function, not JavaScript
- The function resumes where it left off
Part 1async functions
So today we meet the most loved feature of modern JavaScript. async, and await. Now if you understood promises in the last two episodes, this will feel like magic. And by the end, you'll know exactly what await pauses, and what it doesn't, which most developers get wrong. It's a big topic, so we'll take it in two parts.
So here's our road map. Today, part one. What async does. What await does. Two awaits with two timers. And what really happens behind the scenes, in the call stack. Next time, part two. Real fetch calls, error handling, interview answers, and then the big question, async or then? So write these down, and tick them off as we go. Now let's start with async.
1async function getCourse() {2 return "Inside JavaScript";3}4 5const result = getCourse();6console.log(result);7// Promise {<fulfilled>: "Inside JavaScript"}8 9result.then((value) => console.log(value));10// Inside JavaScriptSo put the word async in front of a function, and it becomes an async function. And here's the first rule. An async function always returns a promise. Now look. getCourse returns a plain string, Inside JavaScript. But when we call it and log the result, we don't get the string. We get a promise, fulfilled with that string. async wrapped our value inside a promise, automatically. So to get the value out, we use then, as usual.
1const p = new Promise(function (resolve) {2 resolve("Seats booked!");3});4 5async function getBooking() {6 return p;7}8 9getBooking().then((value) => console.log(value));10// Seats booked!And now what if the async function returns a promise itself? Then it doesn't wrap it twice. The promise it returns simply follows p, and settles with the same result. So we still get seats booked, not a promise inside a promise. So either way, the rule holds. Call an async function, and you always get exactly one promise back.
So remember this, and write it in your notes. Every async function hands back a promise. Return a plain value, and it's wrapped in a fulfilled promise. Return a promise, and the result follows it. And if the function throws an error, the promise is rejected. So always a promise, no exceptions.
1async function a() {} // declaration2const b = async function () {}; // expression3const c = async () => {}; // arrow4const shop = {5 async load() {}, // method6};And now async works with every kind of function you already know. A function declaration, a function expression, an arrow function, and even a method inside an object. Just put async in front. They all follow the same rule, and they all return a promise. So you'll see async arrow functions everywhere in modern code, especially in React apps.
Part 2await
Now, the star of the show. await. async and await together have one job, handling promises. But first, let's look at how we handled promises until now.
1const p = new Promise(function (resolve) {2 setTimeout(() => resolve("Ticket confirmed!"), 3000);3});4 5function getData() {6 p.then((value) => console.log(value));7 console.log("Hello there!");8}9getData();10// Hello there!11// (3 seconds later) Ticket confirmed!So here's a promise p that resolves after three seconds, with ticket confirmed. In getData, we attach a then, and then log hello there. Now what's the order? Hello there prints first, immediately. And three seconds later, ticket confirmed. Because then doesn't stop anything. It just registers a callback, and JavaScript moves on. That's correct, but it often confuses people. So the code doesn't run in the order it's written.
1async function handlePromise() {2 const value = await p;3 console.log("Hello there!");4 console.log(value);5}6handlePromise();7// (3 seconds later) Hello there!8// Ticket confirmed!Now with await. We make handlePromise async, and write await p. This time, hello there does not print immediately. The function waits at the await line until p resolves. After three seconds, value gets ticket confirmed, and only then do the next lines run. Hello there, and then ticket confirmed. So the code now runs in the same order you read it, top to bottom. That's the beauty of await.
So remember this. You write await in front of a promise, and it gives you the promise's value directly. No then needed. And await can only be used inside an async function. Write it inside a normal function, and you get a syntax error. Now the one exception is the top level of a JavaScript module, where modern browsers allow await directly. But inside functions, async is a must.
Part 3Two awaits, two timers
Now let's play with timing, because this is exactly where interview questions come from. What happens with two awaits? So grab a pen if you like, and track the seconds along with me.
1const p = new Promise(function (resolve) {2 setTimeout(() => resolve("Ticket confirmed!"), 3000);3});4 5async function handlePromise() {6 console.log("Hi");7 const one = await p;8 console.log("First:", one);9 const two = await p;10 console.log("Second:", two);11}12handlePromise();So first, a warm-up. What if we await the same promise twice? Does the function wait three seconds, and then three more? Let's see. Hi prints immediately. At three seconds, p resolves, and first prints. Then we await p again. But p has already settled, and a settled promise never changes. So the value comes straight back, and second prints right after. So three seconds in total, not six. Interviewers love this one.
1const p1 = new Promise(function (resolve) {2 setTimeout(() => resolve("p1 done"), 3000);3});4const p2 = new Promise(function (resolve) {5 setTimeout(() => resolve("p2 done"), 2000);6});7 8async function handlePromises() {9 console.log("Hi");10 const a = await p1;11 console.log(a);12 const b = await p2;13 console.log(b);14}15handlePromises();Now p1 takes three seconds, and p2 takes two. We await p1 first, then p2. Hi prints immediately. Then the function waits for p1. At three seconds, p1 resolves, and p1 done prints. Now it awaits p2. But here's the twist. p2 already finished, at two seconds! Both timers started the moment the promises were created, not when we awaited them. So p2 done prints right after. So total time, three seconds, not five.
1async function handlePromises() {2 console.log("Hi");3 const b = await p2; // 2 seconds4 console.log(b);5 const a = await p1; // 3 seconds6 console.log(a);7}Now reverse the order. Await p2 first. Hi prints, then at two seconds, p2 done. Then we await p1, which still needs one more second. So at three seconds, p1 done. Same total time, three seconds, but now the messages come one by one. So the lesson? await waits for each promise in the order you write them. But the work inside the promises was already running, side by side.
Part 4What await really pauses
And now the most important question of today. When the function waits at await, is JavaScript waiting? Is the call stack blocked? So let's look behind the scenes.
1const p = new Promise(function (resolve) {2 setTimeout(function () {3 resolve("Ticket confirmed!");4 }, 3000);5});6 7async function handlePromise() {8 console.log("Hi");9 const val = await p;10 console.log("Hello there!");11 console.log(val);12}13 14handlePromise();15console.log("Global code is done");Hi Global code is done Hello there! Ticket confirmed!
Line one creates p, a promise that resolves after three seconds, with ticket confirmed. And handlePromise is an async function. Now watch the call stack carefully. Global is pushed. Line fourteen calls handlePromise, and its context goes on top. Line eight prints Hi. Line nine says, await p. But p isn't ready yet. So does JavaScript freeze here for three seconds? No! handlePromise is suspended, and it leaves the call stack. Its memory is kept safe, but it's not running. So JavaScript moves on. Line fifteen prints, global code is done. The global code finishes, and the call stack is empty. Three seconds later, p resolves, and handlePromise comes back onto the call stack, right where it left off, at line nine. val gets the result. Line ten prints hello there, and line eleven prints ticket confirmed. Then handlePromise is finished.
So remember this. await doesn't block JavaScript. It suspends only that one async function. The function leaves the call stack, with its variables saved, and the call stack is free for everything else. Clicks, timers, other code. When the promise settles, the function is put back on the call stack, and continues from the exact line where it stopped. So JavaScript still waits for none. The function waits, politely, outside. Now think of a chef who puts a dish in the oven. Instead of staring at the oven for thirty minutes, the chef chops vegetables for the next order. When the oven beeps, the chef comes back to that dish. That's exactly what await does.
And now you can see this with your own eyes. Open DevTools, go to Sources, and put breakpoints inside handlePromise. Run it, and watch the call stack panel. handlePromise is there. Then the call stack goes empty while it waits. And then, it's back! Now with two awaits, this happens twice. The function leaves at the first await, comes back, runs until the second await, and leaves again. So try it once, and it sticks forever.
1async function f() {2 console.log("A");3 await null;4 console.log("B");5}6 7f();8console.log("C");In what order do the letters print?
Show the answer
So f starts, and prints A right away. Then, await null. null isn't even a promise! But await still suspends f, and the rest of f is scheduled for later, as a microtask. So JavaScript continues, and prints C. Then f resumes, and prints B. So A, C, B. Even awaiting a plain value gives up the call stack for a moment.
Did you think await blocks JavaScript?
Answer in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.