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!
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…