Suppose I have the following Promise
:
function doSomethingAsynchronous() { return new Promise((resolve) => { const result = doSomeWork(); setTimeout(() => { resolve(result); }), 100); }); }
At which point in time is doSomeWork()
called? Is it immediately after or as the Promise
is constructed? If not, is there something additional I need to do explicitly to make sure the body of the Promise
is run?
The Promise constructor takes a function (an executor) that will be executed immediately and passes in two functions: resolve , which must be called when the Promise is resolved (passing a result), and reject , when it is rejected (passing an error).
The code inside the Promise constructor runs when the promise is created and it runs synchronously which surprises some people. So even without then() everything still runs.
Just to review, a promise can be created with the constructor syntax, like this: let promise = new Promise(function(resolve, reject) { // Code to execute }); The constructor function takes a function as an argument. This function is called the executor function .
Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
Immediately, yes, by specification.
From the MDN:
The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object)
Here it is in the ECMAScript specification (of course harder to read...): http://www.ecma-international.org/ecma-262/6.0/#sec-promise-executor
This guarantee may be important, for example when you're preparing several promises you then pass to all
or race
, or when your executors have synchronous side effects.
Yes, when you construct a Promise
the first parameter gets executed immediately.
In general, you wouldn't really use a promise
in the way you did, as with your current implementation, it would still be synchronous.
You would rather implement it with a timeout, or call the resolve function as part of an ajax callback
function doSomethingAsynchronous() { return new Promise((resolve) => { setTimeout(function() { const result = doSomeWork(); resolve(result); }, 0); }); }
The setTimeout
method would then call the function at the next possible moment the event queue is free
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With