Async I/O and events · Lesson 5 of 18
Event loop: callbacks to async/await
Understand execution order and write asynchronous flow without callback hell.
Node runs synchronous code on the call stack. When I/O starts, Node delegates it and keeps going. Once ready, its callback enters a queue and the event loop runs it when the stack is empty. Promise callbacks (microtasks) run before the next timer.
Call stack
Node/OS performs I/O
Callback queues
Event loop schedules callback
console.log("A")
setTimeout(() => console.log("D"), 0)
Promise.resolve().then(() => console.log("C"))
console.log("B")Callbacks came first; a Promise represents a future result and supports chaining, while async/await is clearer syntax over Promises. await pauses only its function, not the process. Start independent work together with Promise.all rather than awaiting it serially.
Quick question
Order of A/B/Promise/timer in the example?
Exercise
Write loadBoth(a,b) awaiting both values with Promise.all and returning their sum, then print 7.
Expected output: 7
async function loadBoth(a, b) {
}
loadBoth(Promise.resolve(3), Promise.resolve(4)).then(console.log)Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.