javascript - 在 JavaScript 中使用 Promise 实现快速失败的设计
问题描述
我不确定“快速失败”是否是描述这种方法的最佳方式,但自从我开始学习编程以来,我一直被教导设计这样的功能:
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()
) 提出?
解决方案
如果使用async
andawait
而不是.then
,则可以有效地等待 Promise 解决(或拒绝),如果它拒绝,则提前返回:
(async () => {
try {
await doSomethingAsync(param);
} catch(err) {
console.error(err);
return;
}
// Continue on with the rest of the code
})();
const doSomethingAsync = () => new Promise((resolve, reject) => Math.random() < 0.5 ? resolve() : reject('bad'));
(async () => {
try {
await doSomethingAsync();
} catch(err) {
console.error(err);
return;
}
console.log('continuing');
})();
那是我更喜欢的。您也可以使用该.then(onResolve, onReject)
技术,但通常不建议这样做:
function onReject(err) {
console.log(err);
};
doSomethingAsync(param).then(onResolve, onReject);
function onResolve() {
// Continue on with the rest of the code
}
const doSomethingAsync = () => new Promise((resolve, reject) => Math.random() < 0.5 ? resolve() : reject('bad'));
function onReject(err) {
console.log(err);
};
doSomethingAsync().then(onResolve, onReject);
function onResolve() {
console.log('continuing');
}
这将onReject
只处理由doSomethingAsync(param)
. 如果你onResolve
也可以把它扔进它的体内,那么你将不得不将另一个链接.catch
到它上面(这会开始看起来有点乱 - 通常只在一个地方捕获错误会更好)
推荐阅读
- maven - 领域 = 插件>codehaus.mojo:sonar-maven-plugin:3.7.0.1746
- google-sheets - 将包含普通文本和粗体文本的 Google 工作表中的单元格复制到 GMail 会导致整个文本带有粗体
- banking - SWIFT 消息中可以包含阿拉伯字符吗?
- java - 小数点前 8 位和小数点后 2 位的正则表达式表达式不应计算为零
- build - 电子 - process.env.NODE_ENV 即使在生产中也始终是“开发”
- swift - “弱”可能只适用于类和类绑定协议类型,而不是“ContentView”我缺少什么?
- javascript - 反应原生无法订阅美居后端通知
- android - 如何通过proguard Android混淆包中存在的类?
- python - Same data when connection to multiple wsdl clients using zeep
- java - 如果在 testng.xml 中使用两个或多个类,Appium 应用程序会给出空指针异常