我不确定“快速失败”是否是描述这种方法的最佳方法,但是自从我开始学习编程以来,我总是被教导设计这样的函数:
function doSomething() {
... // do error-prone work here
if (!allGood) {
// Report error,cleanup and return immediately. Makes for cleaner,// clearer code where error-handling is easily seen at the top
...
return;
}
// Success! Continue on with (potentially long and ugly) code that may distract from the error
}
正因为如此,我试图像这样调用一个承诺函数:
doSomethingAsync(param).catch(err => {
console.error(err);
}).then(() => {
// Continue on with the rest of the code
});
但是,这使我的行为类似于经典finally
语句的try...catch...finally
块,即then()
块将被始终调用,即使在错误。有时候这很有用,但是我很少发现自己需要这种功能(或者一般来说,try...catch
语句)。
因此,为了尽可能快速,清晰地排除故障,有没有一种方法可以使我上面的第二个示例按我期望的方式工作(即,then()
仅在{{1} }不是,但是一个catch()
仍会捕获catch()
引发的所有错误吗?