Sub topic 1
Why JavaScript Needs Asynchronous Code: The Event Loop
Prerequisites
This chapter assumes you know JavaScript functions, including arrow functions, and you know how callbacks work. It also assumes basic try/catch and that you can run code in Node.js or a browser console.
The Event Loop
JavaScript runs on a single thread, so only one piece of code runs at a time. A slow synchronous task, such as waiting on a network response, would freeze the whole page. To avoid this, the runtime hands slow work to the host (the browser or Node.js). When that work finishes, the host queues a callback. The event loop runs queued callbacks one at a time, and only once the current code has finished.
Promises: Pending, Fulfilled, and Rejected
A Promise is an object that stands for a result that may not exist yet. It starts out pending. It then settles exactly once, either as fulfilled with a value or as rejected with a reason.
const coinFlip = new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve('heads') : reject(new Error('tails'));
}, 500);
});Chaining with then, catch, and finally
The then method returns a new Promise, so you can chain calls one after another. A rejection skips the then handlers below it until it reaches a catch. The finally handler runs whichever way the Promise settles.
Promise.resolve(2)
.then(n => n * 10)
.then(n => { throw new Error(`bad ${n}`); })
.then(() => console.log('skipped'))
.catch(err => console.log(err.message)) // bad 20
.finally(() => console.log('done'));A common error is forgetting to return inside a then callback. When that happens, the next step receives undefined and doesn't wait for the inner work.
Async Functions Always Return a Promise
The async keyword wraps a function's result in a Promise. A returned value becomes the fulfilled value, and a thrown error becomes the rejection reason.
async function getNumber() {
return 42;
}
console.log(getNumber() instanceof Promise); // true
getNumber().then(value => console.log(value)); // 42Exercise
What does this log, and in what order? async function f() { throw new Error('x'); } f().catch(e => console.log('caught', e.message)); console.log('after');
Show answer
It logs "after" first and then "caught x". The throw rejects the returned Promise instead of throwing at the call site, and the catch handler runs asynchronously after the current synchronous code finishes.