Callbacks & Promises
Why async?
Network requests, timers and file reads take time. JavaScript runs on one thread, so instead of freezing while it waits, it starts the task and continues, then handles the result later. The event loop makes this work.
Callbacks: the old way
setTimeout(() => console.log("1 second later"), 1000);
Many nested callbacks become hard to read ("callback hell").
Promises: a value that arrives later
A promise is pending, then either fulfilled (it has a value) or rejected (it has an error).
fetch(url)
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err))
.finally(() => hideSpinner());
Running several at once
| Method | Resolves when |
|---|---|
Promise.all([a, b]) | all succeed (fails fast if one fails) |
Promise.allSettled([a, b]) | all finish, with each one's result or error |
Promise.race([a, b]) | the first one finishes |
Promise.any([a, b]) | the first one succeeds |
Creating your own
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
Order of execution
Synchronous code runs first, then promise callbacks (microtasks), then timers (macrotasks). That's why setTimeout(fn, 0) runs after Promise.resolve().then(fn).
Example
console.log("1: start");
setTimeout(() => console.log("4: timeout"), 0);
Promise.resolve().then(() => console.log("3: promise"));
console.log("2: end");
// Order: 1, 2, 3, 4
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
Promise.all([wait(300).then(() => "A"), wait(100).then(() => "B")])
.then((results) => console.log(results)) // ["A", "B"] after ~300ms
.catch((err) => console.error(err));