why throw inside of an setTimeout, located inside a promise, doesn't change state and result of the output promise?

30 Views Asked by At

I know existence of a throw inside of a promise, change the state of that specific promise to rejected and the result will be the error message, but when I type this throw inside of a setTimeout located inside of a promise, that throw doesn't modify the state and result of that promise, at first I thought maybe there is something wrong with setTimeout, but I tried resolve() and reject() inside that setTimeout and I received the expected result. so I wonder why this happen with a throw located in setTimeout inside of a promise?

code:

const test = new Promise((resolve, reject) => {
setTimeout(() => {
    throw new Error("error");
}, 2000)
});

//output after 2 sec: [[PromiseState]]: pending
                    //[[PromiseResult]]: undefined;
 const test = new Promise((resolve, reject) => {
 setTimeout(() => {
    resolve("success");
 }, 2000)
 });

 //output after 2 sec:[[PromiseState]]: fulfilled
                    //[[PromiseResult]]: success
2

There are 2 best solutions below

0
Peter B On

The Error is thrown in the context of the setTimeout callback function and it only exists in that context.

The Promise does not know what happens inside that callback, until/unless you make it call resolve or reject.

1
rsjump On

Change your setTimeout callback to:

setTimeout(() => {
    reject(new Error("error"))
}, 2000)