I can't catch reject in my function. I have searched at google, but I haven't found solution, so please help me with this piece of code:
async function errorFunc(){
setTimeout(() => {
return Promise.reject("Any error occured!");
}, 1000);
}
async function main(){
await errorFunc().catch((error)=>{
console.log("E in catch:", error);
});
try{
await errorFunc();
}catch(e){
console.log("E in try-catch:", e);
}
}
main();
No one of that catch (in main() function) works...In console, there is simply printed (twice) this error message:
Uncaught (in promise) Any error occured!
I want to catch that error (or better say promise rejection). How can I do that in my main() function?
Thanks!
errorFuncis not returning the Promise you reject, so it cannot be caught. Something like this should workreturn new Promise((resolve, reject) => setTimeout(() => reject('Any error occurred!'), 1000));asyncmakes it return a Promise. But if you don't useawaitanywhere in that function, that Promise is fullfilled immediatly (resolved, in this case). Whatever you do in the Timeout is no longer related to that Promise. Explicitly returning a "home-made" promise is needed if you want to keep a handle to it in your Timeout, so you can resolve it or reject it