Creating a Promise with the Constructor
You'll learn how to manually create a promise using the Promise constructor and its executor function.
The Core Idea
When you need to wrap asynchronous operations (like timers or callbacks) into a promise, you use the Promise constructor. You pass it an executor function that receives two special arguments: resolve and reject. These are functions that you call to settle the promise—either successfully with resolve() or with an error using reject().
The basic syntax looks like this:
const myPromise = new Promise((resolve, reject) => {
// Your async logic here
});
Think of it like making a pledge: when you create the promise, you're setting up the conditions under which you'll either keep your word (resolve) or admit failure (reject).
How It Works
const promise = new Promise((resolve, reject) => {
// Simulate async work
setTimeout(() => {
const success = true;
if (success) {
resolve("Operation succeeded!");
} else {
reject(new Error("Operation failed"));
}
}, 1000);
});
promise.then(result => console.log(result)); // "Operation succeeded!"
The executor function runs immediately when you create the promise. Inside it, you perform your asynchronous work, then call resolve(value) when done successfully or reject(error) if something goes wrong. This transitions the promise from its pending state to either fulfilled or rejected.
Key Takeaway: Use new Promise((resolve, reject) => {}) to create a promise where you control when and how it settles by calling resolve() for success or reject() for failure inside the executor function.