Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  168] [ 4]  / answers: 1 / hits: 27773  / 7 Years ago, wed, march 29, 2017, 12:00:00

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!


More From » node.js

 Answers
130

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.


[#58346] Monday, March 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
acaciac

Total Points: 317
Total Questions: 117
Total Answers: 128

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;