Mixing Callbacks with Async/Await
You'll learn why combining callback-based APIs with async/await requires careful wrapping to avoid subtle bugs.
The Core Problem
Async/await was designed to work with Promises, not callbacks. When you try to await a callback-based function (like setTimeout, many Node.js APIs, or older libraries), the await keyword simply doesn't work as expected—it has nothing to unwrap because callbacks don't return Promises.
The pitfall: you might think awaiting a callback-based function will pause execution, but it won't. The function returns immediately (usually undefined), and your callback executes later, completely outside your async flow.
The Broken Pattern
async function broken() {
// This doesn't work! setTimeout returns a timer ID, not a Promise
await setTimeout(() => {
console.log("Done");
}, 1000);
console.log("This prints immediately!");
// Output: "This prints immediately!" then "Done" after 1 second
}
The Solution: Promisify First
You must wrap callback-based functions in a Promise before using await:
function delay(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function fixed() {
await delay(1000); // Now await actually waits!
console.log("This prints after 1 second");
}
Think of it like plugging in an adapter—callbacks speak a different language than async/await, so you need a translator (Promise) between them.
Key Takeaway: Callback-based functions cannot be directly awaited; you must wrap them in a Promise constructor that calls resolve (or reject) inside the callback to bridge the two worlds.