不能从异步承诺执行程序函数中抛出错误 [英] Can't throw error from within an async promise executor function
问题描述
我一直试图理解为什么下面的代码没有捕获 throw
。如果从新Promise中删除
部分),那么它可以正常工作,因此它与Promise执行程序是异步函数有关。 async
关键字(async(resolve,...
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>>");
// ...
});
}
答案此处,这里,这里重复如果你'回覆 在任何其他异步回调中,您必须使用 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).
如果不是抛出
我们使用拒绝
,上面的代码工作正常。我想明白,从根本上,为什么 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!
推荐答案
这是 承诺
构造函数反模式!
This is the async/await version of the Promise
constructor antipattern!
永远不要 曾经使用异步函数
作为 Promise
执行函数(即使你能使它工作 1 )!
Never ever use an async function
as a Promise
executor function (even when you can make it work1)!
[1:通过致电解决
和拒绝
而不是使用返回
和抛出
语句]
[1: by calling resolve
and reject
instead of using return
and throw
statements]
byasynchronous他们不是指
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.
< a href =https://stackoverflow.com/a/28692824/1048572> 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屋!