未等待的未处理错误Promise转警告?为何await执行阻塞进程
未处理的Promise拒绝导致进程终止的原因与解决方法
问题原因
Node.js 默认会将未处理的Promise拒绝(即没有通过.catch()捕获、也没有被await并在try/catch中处理的Promise错误)视为严重错误,触发unhandledRejection事件,而该事件的默认行为就是终止当前进程。
你的代码流程里:
codeWithUnhandledPromise函数中创建了notAwaited这个Promise,它的then回调会抛出错误,但这个Promise既没有被await,也没附加错误处理逻辑。- 接着执行
await fsProm.stat(__filename),这会让出事件循环,等待文件状态查询完成。 - 在事件循环的下一个阶段,
notAwaited的then回调执行并抛出错误,此时没有任何代码捕获这个错误,触发了unhandledRejection,Node.js直接终止进程,导致后续所有代码(包括console.log('Not reached')、main里的try/catch/finally回调等)都无法执行。
解决方法
你有几种方式避免进程被终止:
1. 给未等待的Promise添加错误捕获
直接给notAwaited附加.catch(),把错误转为警告输出,这样就不会触发unhandledRejection:
const notAwaited = Promise.resolve().then(function(){ throw new Error('Irrelevant'); }).catch(err => console.warn('警告:', err.message)); // 捕获错误并转为警告
2. 全局修改unhandledRejection的默认行为
如果你的项目中有大量类似未处理的Promise拒绝,且都希望转为警告而非终止进程,可以全局监听unhandledRejection事件:
// 在代码最顶部添加 process.on('unhandledRejection', (reason, promise) => { console.warn('未处理的Promise拒绝:', reason.message); // 不要调用process.exit(),进程就会继续执行 });
3. 等待该Promise并处理错误
如果这个Promise的结果其实需要关注,最好的方式还是await它,并在try/catch中捕获错误:
async function codeWithUnhandledPromise(){ try { await Promise.resolve().then(function(){ throw new Error('Irrelevant'); }); } catch (err) { console.warn('警告:', err.message); } await fsProm.stat( __filename ); console.log( 'Not reached' ); }
修改后的完整代码示例(方案1)
const fsProm = require('fs').promises; async function codeWithUnhandledPromise(){ const notAwaited = Promise.resolve().then(function(){ throw new Error('Irrelevant'); }).catch(err => console.warn('警告:', err.message)); await fsProm.stat( __filename ); console.log( '现在可以执行到这里了' ); } async function main(){ try { await codeWithUnhandledPromise(); } catch (error) { console.log( '捕获到错误:', error.message ); } finally { console.log( 'Finally执行' ); } } main().catch(function(err){ console.log( 'Main的catch捕获:', err.message ); }); console.log( 'done' );
内容的提问来源于stack exchange,提问作者CSeitel
相关产品推荐
相关产品推荐

