new Promise()
ES6+Creates a new Promise object with an executor function that receives resolve and reject callbacks.
Syntax
new Promise(executor)Parameters
executor Function A function that receives resolve and reject functions as parameters
Return Value
A new Promise object
Examples
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('완료!');
}, 1000);
});
promise.then(value => console.log(value)); 📌 When to Use
Use new Promise() when wrapping callback-based APIs, creating delays, or building custom async operations that require manual resolution control.
⚠️ Common Mistakes
Creating a Promise constructor when async/await or Promise.resolve() would suffice.
Forgetting to call resolve() or reject(), leaving the promise pending forever.
Throwing errors outside the executor instead of using reject() - they become unhandled.
✅ Best Practices
Errors thrown inside the executor automatically reject the promise - no try-catch needed inside.
Call resolve/reject only once - subsequent calls are ignored.
⚡ Performance Notes
Creating promises has minimal overhead, but avoid creating them unnecessarily. Use util.promisify() in Node.js for callback conversion instead of manual wrapping.
🌍 Real World Example
Promisified setTimeout
Create a delay function that works with async/await.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function animateSequence() {
console.log('Step 1: Fade in');
await delay(1000);
console.log('Step 2: Wait');
await delay(500);
console.log('Step 3: Fade out');
await delay(1000);
console.log('Animation complete!');
}
// Promisify callback-based API
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (error, data) => {
if (error) reject(error);
else resolve(data);
});
});
}
animateSequence();