5

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?

mjs
  • 63,493
  • 27
  • 91
  • 122

2 Answers2

6

Yes, it is guaranteed. The specification of Promise has this step which will always be evaluated:

  1. 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.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Or simply put: The executor function `() => console.log("HERE")` passed to the `Promise` constructor is always executed immediately. –  Jul 04 '16 at 10:07
  • @LUH3417 Yes, but the OP wanted to know if it was guaranteed, hence the quotes from and references to the spec showing where and how it is called, and therefore _why_ it's guaranteed. – James Thorpe Jul 04 '16 at 10:11
  • No offense, just for users who are not familiar with "spec speech" –  Jul 04 '16 at 10:13
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).

Marco Castelluccio
  • 10,152
  • 2
  • 33
  • 48
  • Ah good point, that's … unfortunate! I guess I can live with the cache entry not always being deleted, although I'm not sure how to deal with the possibility that it might happen frequently. – mjs Feb 03 '16 at 23:44