为什么旧代码会这样做?
从历史上看,旧的(2013年之前)promise 库"吞下"了你自己没有处理过的未经处理的promise 拒绝.从那以后,任何书面文件都没有出现这种情况.
今天发生了什么?
浏览器和 node .js已经自动记录未捕获的promise 拒绝或有处理它们的行为,并将自动记录它们.
此外,通过添加.catch
,您正在向调用函数undefined
的方法发送信号:
// undefined if there was an error
getStuff().then(stuff => console.log(stuff));
在编写异步代码时,人们应该问自己的问题通常是"同步版本的代码会做什么?"
function calculate() {
try {
const stuff = generateStuff();
return process(stuff);
} catch (err) {
console.error(err);
// now it's clear that this function is 'swallowing' the error.
}
}
我认为如果出现错误,消费者不会期望这个函数返回undefined
.
总而言之,人们不赞成它,因为它让应用程序流程中的开发人员感到惊讶,而且浏览器在今天仍然会记录未捕获的promise 错误.
如何取而代之:
Nothing.这就是它的美妙之处——如果你写道:
async function getStuff() {
const stuff = await fetchStuff();
return process(stuff);
}
// or without async/await
const getStuff = fetchStuff().then(process);
首先,你会得到大约anyway个更好的错误:)
如果运行的是旧版本的Node,该怎么办.js?
Node的旧版本.js可能不会记录错误或显示弃用警告.在这些版本中,您可以使用console.error
(或适当的日志(log)记录工具)globally:
// or throw to stop on errors
process.on('unhandledRejection', e => console.error(e));