Is the code below guaranteed to output HERE
?
var p = new Promise(() => console.log("HERE"))
(That is, does var p = new Promise(fn)
always execute fn
if p.then(…)
is never called to do something with the result?)
More specifically, in the context of service workers, if I call Cache.delete()
but never call .then()
on the return value (or I throw away the return value), is the cache entry guaranteed to be deleted?
As soon as the javascript Interpreter sees a promise declaration. It immediately executes its implementation synchronously. Even though it will get settled eventually.
A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection. Promises are eager, meaning that a promise will start doing whatever task you give it as soon as the promise constructor is invoked.
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 constructor syntax for a promise object is: let promise = new Promise(function(resolve, reject) { // executor (the producing code, "singer") }); The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically.
Yes, it is guaranteed. The specification of Promise
has this step which will always be evaluated:
- Let completion be Call(executor, undefined, «resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]]»).
where executor
is what you passed to the Promise
constructor, and Call results in that code being run. This all happens before the Promise
is even returned to your p
variable.
As James said, it is guaranteed that the function will be called. Though this doesn't guarantee that the cache entry gets deleted!
You have to check the value of the promise resolution (true
if the cache entry is deleted, false
otherwise).
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