In this lesson, you stepped into Node’s REPL with a log before, inside and after a call to an async function, and watched the caller carry on while the function waited.
Key Points
- A common guess is that
awaitstops everything until the value arrives, the way code waits when it runs top to bottom. It doesn’t. wait()from Wrap a Callback API in a Promise gives back a promise that’s fulfilled after the number of milliseconds you pass. Here,wait(300)stands in for the kiosk’s slow answer.- A line that logs
welcome, callsload()and then logsmenu shownprintswelcome,loading, thenmenu shown. The REPL’s prompt comes back whileload()is still waiting, andloadedprints last, 300 milliseconds later. - Your line runs on the call stack, logs
welcome, and callsload(), which logsloading. On theawaitline,wait(300)runs first. Its timer goes to the waiting area, and it gives back a pending promise. Thenload()steps aside. It leaves the stack and hands its own promise back to your line, still pending. Your line carries on and logsmenu shown. - When the timer is due, it joins the task queue, and the event loop moves it onto the empty stack. Its callback fulfills the promise from
wait(), soload()picks up right after itsawait, logsloaded, and its own promise is fulfilled. Howload()gets back onto the stack in detail comes later in the course. - Carrying on is useful, because the rest of your program keeps going while the kiosk is slow.
- When the next line needs the result, the caller awaits the promise
load()hands back, as your loop over Tolu’s picks did withplanPick(). Withawait load();, the order iswelcome,loading,loaded, thenmenu shown. At the top level of a module or the REPL,awaitpauses the rest of the module or line, not Node’s event loop, which still runs the timer.
The rule is that await pauses the function it’s in, not the program. Only code after the await, in the same function, waits.