javascriptpromise

Why is promise object resolved at different times even after the same amount of delay?


Screenshot

Code1:

let p = new Promise((resolve,reject) => {
    setTimeout(() => {console.log("itsdone"); resolve("done");},10000);
});

Code2:

let p = new Promise((resolve,reject) => {
    setTimeout(resolve("done"),10000);
});

Even though same delay of 10s has been provided, why the promise object's (p) state differs in the two code scenarios? The promise in Code1 is resolved after 10s, but in Code2 it is resolved instantaneously? Please see the attached image for the difference in outputs.

Isn't the promise in Code2 is also expected to be resolved in 10s.


Solution

  • The use of parenthesis on your syntax (see: resolve(someValue)) implies function calling. Therefore, you are running the resolve function, and passing the result into the setTimeout() function as callback.

    If you want to resolve after the timeout, the best you can do is pass an anonymous function that runs the resolve function with your desired value (As seen on your first example). You could shorten it like this:

    setTimeout(() => resolve("Hello World"), 10000);
    

    Anonymous functions can simply have its return value without curly braces if your function only consists of a single statement.