When to Use the Constructor
You'll learn when the Promise constructor is actually needed—and when it's not.
When the Constructor Is the Right Tool
The Promise constructor is your bridge between the old callback world and modern Promise-based code. You should reach for new Promise() in two specific scenarios:
1. Wrapping Legacy Callback APIs
When working with older libraries or Node.js APIs that use error-first callbacks, the constructor lets you "promisify" them:
function readFilePromise(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
2. Creating Custom Async Logic from Scratch
When you need to build asynchronous behavior that doesn't come from an existing Promise-returning API:
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
When NOT to Use the Constructor
If you're already working with Promises, don't wrap them in another Promise—that's the anti-pattern from the previous lesson. Just return the existing Promise or chain with .then().
Bad (unnecessary wrapping):
function getUser(id) {
return new Promise((resolve, reject) => {
fetch(`/users/${id}`)
.then(data => resolve(data))
.catch(err => reject(err));
});
}
Good (return the Promise directly):
function getUser(id) {
return fetch(`/users/${id}`);
}
Key Takeaway: Use the Promise constructor only when integrating callback-based code or building custom async primitives. If you already have a Promise, work with it directly.