Wrapping Async Operations
You'll learn how to convert callback-based asynchronous functions into promise-returning functions using the Promise constructor.
The Core Problem
Most older JavaScript APIs—especially in Node.js—use error-first callbacks. You've learned how to create promises with the constructor, but one of its most practical uses is wrapping existing callback-based functions so they return promises instead.
How Wrapping Works
When you wrap an async operation, you:
- Create a new Promise with the constructor
- Inside the executor, call the callback-based function
- In the callback, check for errors and either
rejectorresolve
This transforms the API from callback-style to promise-style.
Example Pattern
function readFilePromise(filename) {
return new Promise((resolve, reject) => {
// Call the callback-based API
readFile(filename, (error, data) => {
if (error) {
reject(error); // Error path
} else {
resolve(data); // Success path
}
});
});
}
Now instead of using callbacks, you can use .then() and .catch():
readFilePromise('data.txt')
.then(data => console.log(data))
.catch(error => console.error(error));
Why This Matters
Wrapping lets you gradually modernize callback-heavy codebases. You keep the old API underneath, but expose a promise-based interface on top. This eliminates callback hell and makes your async code chainable and easier to read.
Key Takeaway: The Promise constructor is your bridge from callback-based APIs to promise-based code—wrap the old API in a new Promise, call resolve on success, and reject on error.