skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. Change your setTimeout callback to:

    setTimeout(() => {
        reject(new Error("error"))
    }, 2000)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search