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
The Error is thrown in the context of the
setTimeoutcallback function and it only exists in that context.The Promise does not know what happens inside that callback, until/unless you make it call
resolveorreject.