Why can't Promise catch errors?

console.log("here we go");
new Promise( resolve => {
   setTimeout( () => {
        console.log(2)
        throw new Error("bye");//
    }, 2000);
   //    throw new Error("bye");//
}).then( value => {
    console.log( value + " world");
})
.catch( error => {
    console.log( "Error:", error.message);
});
Apr.21,2022

first of all, in non-async functions, try-catch cannot catch exceptions generated in asynchronous operations. Promise / setTimeout are typical asynchronous operations.
secondly, catch of Promise is triggered before resolve is called throw 's Error object, or reject is called.
finally, setTimeout is an asynchronous operation, which will not be executed until the current operation is executed, so the current try-catch cannot handle the exception of setTimeout callback.

synthesize the above three points,

  1. your throw is in setTimeout , and there is no reject , Promise cannot catch to
  2. if you move to the next sentence of setTimeout , it is equivalent to your Promise without resolve before throw Error

new Promise( (resolve, reject)=> {
setTimeout( () => {

    console.log(2)
    reject('bye');
}, 2000);
})

isn't this an error caught

Menu