Synchronous Errors in the Executor
What you'll learn: How JavaScript automatically handles errors thrown inside a Promise executor function.
The Automatic Safety Net
When you create a Promise using the constructor, you pass in an executor function. This function runs immediately and synchronously when the Promise is created. But what happens if your executor code throws an error?
Here's the good news: JavaScript automatically catches any synchronous error thrown in the executor and converts it into a promise rejection. You don't need to manually wrap everything in try-catch blocks.
How It Works
const promise = new Promise((resolve, reject) => {
throw new Error('Something went wrong!');
// This line never runs
resolve('success');
});
// The promise is now rejected with the error
This is exactly equivalent to calling reject() explicitly:
const promise = new Promise((resolve, reject) => {
reject(new Error('Something went wrong!'));
});
Both promises end up in the rejected state with the same error.
Why This Matters
This automatic error handling prevents uncaught exceptions from crashing your program. Any synchronous mistake—typos, reference errors, or intentional throws—gets safely wrapped into the promise's rejection:
const promise = new Promise((resolve, reject) => {
const result = nonExistentFunction(); // ReferenceError!
resolve(result);
});
// Promise is rejected with: ReferenceError: nonExistentFunction is not defined
Key Takeaway: If the executor function throws an error synchronously, JavaScript automatically rejects the promise with that error, giving you a built-in safety mechanism for synchronous failures.