From callbacks to promises to async/await
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
The same problem, three styles
Reading a user from a database, then their orders, then the products in those orders. Each step takes time, and each depends on the one before. JavaScript has solved this problem three times, each better than the last. You will meet all three in real code, so we will look at them in order.
Style 1: callbacks
The first approach is to pass a function to be called when the work is done.
function getUser(id, callback) {
setTimeout(() => callback(null, { id, name: "Sara" }), 100);
}
getUser(1, (error, user) => {
if (error) return console.log("Failed", error);
console.log(user.name);
});
By convention the first argument of the callback is the error, or null. This works for one step. For several steps in a row, the callbacks nest inside each other:
getUser(1, (err, user) => {
getOrders(user.id, (err, orders) => {
getProducts(orders[0].id, (err, products) => {
console.log(products); // callback hell
});
});
});
The code drifts to the right, error handling is repeated at every level, and it is hard to read. This shape has a name, "callback hell", and it is why promises were invented.
Style 2: promises
A promise is an object that stands for a value that is not available yet. It is always in one of three states: pending, fulfilled (with a value) or rejected (with an error). Once it settles, it never changes.
You can create one with new Promise, and you call resolve or reject when the work finishes:
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid id"));
else resolve({ id, name: "Sara" });
}, 100);
});
}
You consume a promise with .then for success, .catch for failure, and .finally for cleanup:
getUser(1)
.then(user => {
console.log(user.name);
return getUser(2); // returning a promise continues the chain
})
.then(user2 => console.log(user2.name))
.catch(error => console.log("Failed:", error.message))
.finally(() => console.log("done"));
The chain is flat. Each .then receives the value returned by the previous one, and if it returns a promise, the chain waits for it. One .catch at the end handles an error from any step above it.
Style 3: async and await
async/await is a way of writing promise code so that it looks synchronous. Mark a function async, and inside it you can await a promise. The function pauses until the promise settles, but the rest of the program keeps running.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid id"));
else resolve({ id, name: "Sara" });
}, 100);
});
}
async function main() {
try {
const user = await getUser(1);
console.log("Got", user.name);
await wait(200);
const bad = await getUser(0); // rejects, so jumps to catch
console.log("never printed", bad);
} catch (error) {
console.log("Failed:", error.message);
} finally {
console.log("Finished");
}
}
main();
console.log("main() has started, this prints first");
The output order is: the "has started" line first, then "Got Sara", then "Failed: Invalid id" and "Finished". The call to main() runs until its first await, then returns control to the caller. Everything after an await continues later, in the microtask queue we discussed in the event loop lesson.
Two facts to remember:
- An
asyncfunction always returns a promise. If youreturn 5, the caller gets a promise that resolves to 5. awaitcan only be used inside anasyncfunction, or at the top level of an ES module.
Errors work the way you would hope: a rejected promise becomes a thrown exception at the await, so ordinary try/catch handles it.
Running things in parallel
A common slip is to await independent jobs one after another:
const a = await fetchA(); // waits 1 second
const b = await fetchB(); // then waits another second
If fetchB does not need the result of fetchA, start them both and wait together with Promise.all:
const [a, b] = await Promise.all([fetchA(), fetchB()]);
This takes as long as the slowest one, not the sum. Promise.all fails as soon as any promise fails. If you want every result whether it succeeded or not, use Promise.allSettled. Promise.race gives you the first one to settle, which is a way to build a timeout. Promise.any gives the first one to succeed.
const results = await Promise.allSettled([getUser(1), getUser(0)]);
console.log(results.map(r => r.status)); // ["fulfilled", "rejected"]
Await in loops
await inside a for...of loop runs the steps one by one, which is correct when order matters. forEach does not wait for async callbacks, so this does not work as you would expect:
ids.forEach(async id => {
await getUser(id); // forEach does not wait for these
});
console.log("this runs before they finish");
Use for...of for sequence, or await Promise.all(ids.map(getUser)) for parallel.
Which style should you use
I write async/await for nearly everything. It reads in order, and try/catch works as usual. I use .then for short one-liners and Promise.all and friends for combining. Callbacks stay for event handlers and older APIs. If you must use a callback-based API, wrap it in a promise once, as we did with wait, and use await after that.
Common mistakes
- **Forgetting to
await.** You get a pending promise, not the value.console.log(getUser(1))printsPromise { <pending> }. - **Forgetting the
asynckeyword.**awaitinside a normal function is a syntax error. - Awaiting jobs in sequence that could run in parallel. Use
Promise.all. - Not handling rejections. An unhandled rejected promise is an error in Node and a console warning in the browser.
- **Using
asyncwithforEach.** It does not wait. - **Writing
new Promisearound something that already returns a promise.** Return it directly.
Try it yourself
- Convert the nested callback example to promises, then to
async/await. - Use
waitto build a functioncountdown(n)that logs n, n-1, ... 1 with one second between lines. - Start three
wait(300)calls. Measure the time withPromise.alland with sequentialawait. Compare. - Write
withTimeout(promise, ms)usingPromise.racethat rejects if the promise takes too long.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid id"));
else resolve({ id, name: "Sara" });
}, 100);
});
}
async function main() {
try {
const user = await getUser(1);
console.log("Got", user.name);
await wait(200);
const bad = await getUser(0); // rejects, so jumps to catch
console.log("never printed", bad);
} catch (error) {
console.log("Failed:", error.message);
} finally {
console.log("Finished");
}
}
main();
console.log("main() has started, this prints first");
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account