Promise Executors Must Not Be Async
An async executor swallows its own rejection so the outer promise stays pending forever; keep executors synchronous and chain async work from them.
Code
// async executor(执行器)抛出的错误只会拒绝它内部的匿名 promise:
// 外层 new Promise 触达不到这个拒绝,永远 pending
process.on('unhandledRejection', (reason) => {
console.log('unhandled rejection:', reason.message);
});
function brokenWork() {
return new Promise(async (resolve, reject) => {
await Promise.resolve();
throw new Error('cleanup skipped');
});
}
const ghost = brokenWork();
let settled = false;
ghost.then(
() => { settled = true; },
() => { settled = true; },
);
setTimeout(() => console.log('broken settled?', settled), 10);
// 正确形态:同步执行器,异步工作通过返回的 promise 链式上报
function safeWork() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('surface properly')), 5);
});
}
safeWork().catch((error) => console.log('caught:', error.message));How it works
Promise Executors Must Not Be Async keeps everything in the functions brokenWork and safeWork.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. There is no validation gate in front of the Error — the throw fires whenever its line runs.
It builds and returns a fresh value rather than reusing its inputs.
Using it
Entry signature: function brokenWork()
The demo output is labeled (unhandled rejection:, broken settled?, caught:), so every printed line maps back to its originating operation.
Key statements
return new Promise(async (resolve, reject) => {
await Promise.resolve();
throw new Error('cleanup skipped');
});
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('surface properly')), 5);
});
process.on('unhandledRejection', (reason) => {
console.log('unhandled rejection:', reason.message);
});
Interactive Tools for This Topic
FAQ
- Does `brokenWork` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Does the snippet validate its input?
- No. There is no input validation in the snippet — the `Error` is raised unconditionally at its site, with no check in front of it.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `brokenWork`, `safeWork` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.