Can#39;t throw error from within an async promise executor function(不能从异步承诺执行器函数中抛出错误)
问题描述
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>>");
// ...
});
}
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).
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!
Never ever use an async function
as a Promise
executor function (even when you can make it work1)!
[1: by calling resolve
and reject
instead of using return
and throw
statements]
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(…);
})
which is equivalent to
new Promise(function() {
return delay(…).then(function() {
throw new Error(…);
});
})
where it's clear now that the throw
is inside an asynchronous callback.
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.
这篇关于不能从异步承诺执行器函数中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不能从异步承诺执行器函数中抛出错误
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01