我不确定“快速失败”是否是描述这种方法的最佳方式,但自从我开始学习编程以来,我一直被教导设计这样的功能:
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()
仅catch()
在没有执行的情况下执行,但单个catch()
仍然会捕获所有错误由doSomethingAsync()
) 提出?