[英]How to prevent code executing after a fail inside try/catch in JS
我在 async IIFE 中有一个 JS try/catch 结构(在此处未显示的另一个异步结构中)
await (async function() {
try {
await myFunc1(),
await myFunc2(),
await myFunc3(),
} catch (e) {
logger.info(e)
}
})();
如果任何 myfuncs 失败,我希望看到脚本停止。 试过 promise 全部
await (async function() {
try {
Promise.all([
await myFunc1(),
await myFunc2(),
await myFunc3(),
]).then(values => {
console.log(values);
});
} catch (e) {
logger.info(e)
}
})();
但是 func2 和 func3 在 func1 失败后继续。 如果任何功能失败,我应该如何设计代码以停止? (我的错误来自 apicall,它给出 400 或 500 错误)myfunctions 将一些订单发布到服务器,所以如果第一个失败,其他的就过时了,如果第一个失败,我应该阻止它们继续
只需添加一个throw e;
记录错误后:
// For the demo... const logger = { info: console.log }, myFunc1 = () => Promise.resolve(), myFunc2 = () => Promise.reject("Err in myFunc2"), // rejects myFunc3 = () => Promise.resolve(); async function runAll() { try { await myFunc1(); await myFunc2(); // Rejects await myFunc3(); // Not executed } catch (e) { logger.info(e); throw e; } } (async () => { await runAll(); logger.info('This will not be logged'); // Won't be logged })();
似乎主要问题在 myFunc() 定义中。 我扔了一个e; 在功能 scope 的 catch 块内部,因此它解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.