为何Promise的then回调未被触发?Node.js脚本执行异常排查
问题分析与解决方案
先看看你的代码:
async function main() { console.log("Hello world!"); } main().then(() => "All done").catch(e => console.err(e));
你执行node hello.js后只看到Hello world,没看到All done,核心原因是你对Promise的then回调的作用理解有小偏差,咱们拆解来看:
main()执行时,里面的console.log("Hello world!")会直接触发输出,这部分是正常的。- 因为
main是async函数,它默认返回一个状态为resolved的Promise(没有return的话,就是Promise.resolve(undefined))。 - 你调用
.then(() => "All done")时,这个箭头函数确实返回了字符串"All done",但这个值只是作为后续Promise链的传递值,不会自动被打印到控制台——你没有对这个值做任何输出操作,所以自然看不到它。 - 顺带提一句:你的
catch里写错了,应该是console.error(e),不是console.err(e),不过这不是当前问题的核心。
修正方案
想要得到你预期的输出(不管是分两行还是拼接成一行),可以试试这几种方式:
方式一:在then里直接打印
async function main() { console.log("Hello world!"); } main().then(() => console.log("All done")).catch(e => console.error(e));
方式二:让main返回内容,在then里拼接输出
async function main() { const msg = "Hello world!"; console.log(msg); return msg; } main() .then(msg => console.log(`${msg} All done`)) .catch(e => console.error(e));
方式三:用await简化流程(需要包裹在async函数中)
async function main() { console.log("Hello world!"); } async function run() { await main(); console.log("All done"); } run().catch(e => console.error(e));
简单来说:Promise的then回调返回的值不会自动输出,必须显式调用console.log才能让它出现在控制台里~
内容的提问来源于stack exchange,提问作者gcali
相关产品推荐
相关产品推荐

