Are Promises Lazily Evaluated?
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 cal
Solution 1:
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.
Solution 2:
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).
Post a Comment for "Are Promises Lazily Evaluated?"