Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading