我已经使用 async/await 6 个月了,并且非常喜欢语法糖。我通常以传统方式使用它:
try {
await doSomethingAsync()
}
catch (e) {}
最近我开始尝试不立即等待,以便在等待异步数据之前在此上下文中运行一些额外的代码,例如:
let p = doSometiongAsync()
... do more stuff
await p;
或:
let p1 = doJob1();
let p2 = doJob2();
... do more synchronous stuff ...
await p1;
await p2;
问题是,try/catch block 的正确位置在哪里,以确保正确捕获调用中的错误(同步或异步)。是否围绕初始函数调用:
try {
let p = doSomethingAsync()
} catch(errors) {}
... do stuff ...
await p
或者 try block 围绕 await... 或两个不同的 try block ,每个 block 一个?
try {
let p = doSomethingAsync()
} catch(errors) {}
... do stuff
try {
await p;
} catch (evenmoreerrors) {}
谢谢!
最佳答案
这取决于 doSomethingAsync
是什么:async
函数,或返回 promise 的非 async
函数。
如果是async
函数
...您只需要 await
周围的 try
/catch
; async
函数永远不会同步抛出异常(即使异常是由它的初始同步部分抛出的)。
例子:
async function foo() {
// Note this is in the synchronous portion
console.log("synchronous part of foo");
if (true) {
throw new Error();
}
return new Promise(resolve => {
resolve();
});
}
(async () => {
const p = foo(); // No uncaught error
try {
await p;
} catch (e) {
console.log("Caught the error");
}
})().catch(e => {
console.log("Failed to catch it!");
});
如果它是一个非async
函数返回一个promise
...然后根据函数的不同,您可能需要在这两个地方使用 try
/catch
,也可能不需要,具体取决于它的编写方式。如果它可能会抛出它的同步代码,你需要 try
/catch
解决它。在 promise 拒绝的情况下,您需要 try
/catch
await
。
不处理同步部分的例子:
function foo() {
// Note this is in the synchronous portion
console.log("synchronous part of foo");
if (true) {
throw new Error();
}
return new Promise(resolve => {
resolve();
});
}
(async () => {
const p = foo(); // No uncaught error
try {
await p;
} catch (e) {
console.log("Caught the error");
}
})().catch(e => {
console.log("Failed to catch it!");
});
未能捕捉到 promise 拒绝的示例:
function foo() {
// Note this is in the synchronous portion
console.log("synchronous part of foo");
return new Promise((resolve, reject) => {
reject();
});
}
(async () => {
try {
const p = foo();
} catch (e) {
console.log("Caught the error");
}
await p;
})().catch(e => {
console.log("Failed to catch it!");
});
关于javascript - 使用非立即异步/等待时正确放置 try/catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49607954/