Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 830
mjs Avatar asked Feb 03 '16 12:02

mjs


People also ask

Are promises lazy JavaScript?

As soon as the javascript Interpreter sees a promise declaration. It immediately executes its implementation synchronously. Even though it will get settled eventually.

Are promises eager?

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.

What are the promises and how do they work?

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

How do you make a Promise?

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.


2 Answers

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.

like image 59
James Thorpe Avatar answered Sep 18 '22 18:09

James Thorpe


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

like image 30
Marco Castelluccio Avatar answered Sep 20 '22 18:09

Marco Castelluccio