The Executor Function
You'll learn: How the executor function works when creating a Promise and what its two parameters do.
What Is the Executor?
When you create a Promise using new Promise(), you must pass it a function — this is called the executor function. The executor runs immediately (synchronously) as soon as the Promise is constructed, even before the next line of code executes.
The executor receives two functions as parameters, conventionally named resolve and reject. These are your tools for controlling the Promise's fate:
resolve(value)— Call this to fulfill the Promise with a success valuereject(reason)— Call this to reject the Promise with an error or reason
How It Works
const myPromise = new Promise((resolve, reject) => {
console.log('Executor runs immediately!');
// Simulate async work
const success = true;
if (success) {
resolve('Operation succeeded');
} else {
reject('Operation failed');
}
});
console.log('Promise created');
Output:
Executor runs immediately!
Promise created
Notice the executor ran before "Promise created" logged — it's synchronous!
Key Behavior
You typically call resolve or reject once. Calling either one transitions the Promise from "pending" to either "fulfilled" or "rejected". Additional calls to resolve or reject are ignored — a Promise can only settle once.
Key Takeaway: The executor function runs immediately when you create a Promise and receives resolve and reject functions that you call to settle the Promise's outcome.