无法从异步承诺执行器函数中抛出错误 [英] Can't throw error from within an async promise executor function
问题描述
我一直试图从概念上理解为什么下面的代码没有捕捉到 throw
.如果您从 new Promise(async (resolve, ...
部分) 中删除 async
关键字,则它可以正常工作,因此它与 Promise 执行器是一个异步函数.
I've been trying to get a conceptual understanding of why the following code doesn't catch the throw
. If you remove the async
keyword from the new Promise(async (resolve, ...
part then it works fine, so it has to do with the fact that the Promise executor is an async function.
(async function() {
try {
await fn();
} catch(e) {
console.log("CAUGHT fn error -->",e)
}
})();
function fn() {
return new Promise(async (resolve, reject) => {
// ...
throw new Error("<<fn error>>");
// ...
});
}
答案这里,此处 和 here 重复如果你在任何其他异步回调中,你必须使用 reject
",但通过异步"它们不是指的是 async
函数,所以我不认为他们的解释在这里适用(如果他们适用,我不明白如何).
The answers here, here, and here repeat that "if you're in any other asynchronous callback, you must use reject
", but by "asynchronous" they're not referring to async
functions, so I don't think their explanations apply here (and if they do, I don't understand how).
如果我们使用 reject
而不是 throw
,上面的代码工作正常.我想了解,从根本上,为什么 throw
在这里不起作用.谢谢!
If instead of throw
we use reject
, the above code works fine. I'd like to understand, fundamentally, why throw
doesn't work here. Thanks!
推荐答案
这是 Promise 的 async/await 版本
构造函数反模式!
This is the async/await version of the Promise
constructor antipattern!
从不 永远 使用 async 函数
作为 Promise
执行器函数 (即使你可以让它工作1)!
Never ever use an async function
as a Promise
executor function (even when you can make it work1)!
[1: 通过调用 resolve
和 reject
而不是使用 return
和 throw
语句]
[1: by calling resolve
and reject
instead of using return
and throw
statements]
他们所说的异步"并不是指async
函数,所以我认为他们的解释不适用于这里
by "asynchronous" they're not referring to
async
functions, so I don't think their explanations apply here
他们也可以.它不能工作的一个简单例子是
They could as well. A simple example where it cannot work is
new Promise(async function() {
await delay(…);
throw new Error(…);
})
相当于
new Promise(function() {
return delay(…).then(function() {
throw new Error(…);
});
})
现在很清楚 throw
在异步回调中.
where it's clear now that the throw
is inside an asynchronous callback.
Promise
构造函数只能捕获同步异常,和一个 async 函数
从不抛出 - 它总是返回一个承诺(尽管可能会被拒绝).并且该返回值被忽略,因为 Promise 正在等待 resolve
被调用.
The Promise
constructor can only catch synchronous exceptions, and an async function
never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve
to be called.
这篇关于无法从异步承诺执行器函数中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!