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!
async function errorFunc(){
return new Promise((resolve, reject) => setTimeout(() => reject("Any error occured!"), 1000))
}
this is what you want.
setTimeout(callback, ms)
callback will be exec in global, no one catch it.
I think it printed the same error twice, because in the second function:
try{
await errorFunc();
}catch(e){
console.log("E in try-catch:", error);
}
}
you printed "error" but caught "e", I didn't understand the issue that much but I suppose that that's the reason it printed twice,
maybe swap "error" with "e" to print the other error caught
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With