Why Does the Promise Constructor Need an Executor

Why does the Promise constructor need an executor?

This is called the revealing constructor pattern coined by Domenic.

Basically, the idea is to give you access to parts of an object while that object is not fully constructed yet. Quoting Domenic:

I call this the revealing constructor pattern because the Promise constructor is revealing its internal capabilities, but only to the code that constructs the promise in question. The ability to resolve or reject the promise is only revealed to the constructing code, and is crucially not revealed to anyone using the promise. So if we hand off p to another consumer, say

The past

Initially, promises worked with deferred objects, this is true in the Twisted promises JavaScript promises originated in. This is still true (but often deprecated) in older implementations like Angular's $q, Q, jQuery and old versions of bluebird.

The API went something like:

var d = Deferred();
d.resolve();
d.reject();
d.promise; // the actual promise

It worked, but it had a problem. Deferreds and the promise constructor are typically used for converting non-promise APIs to promises. There is a "famous" problem in JavaScript called Zalgo - basically, it means that an API must be synchronous or asynchronous but never both at once.

The thing is - with deferreds it's possible to do something like:

function request(param) {
var d = Deferred();
var options = JSON.parse(param);
d.ajax(function(err, value) {
if(err) d.reject(err);
else d.resolve(value);
});
}

There is a hidden subtle bug here - if param is not a valid JSON this function throws synchronously, meaning that I have to wrap every promise returning function in both a } catch (e) { and a .catch(e => to catch all errors.

The promise constructor catches such exceptions and converts them to rejections which means you never have to worry about synchronous exceptions vs asynchronous ones with promises. (It guards you on the other side by always executing then callbacks "in the next tick").

In addition, it also required an extra type every developer has to learn about where the promise constructor does not which is pretty nice.

Why does the Promise constructor require a function that calls 'resolve' when complete, but 'then' does not - it returns a value instead?

Bergi's answer is excellent, and has been very helpful to me. This answer is complementary to his. In order to visualize the relationship between the Promise() constructor and the then() method, I created this diagram. I hope it helps somebody... maybe even me, a few months months from now.

The main idea here is that the "executor" function passed to the Promise() constructor sets tasks in motion that will set the state of the promise; whereas the handlers you pass to then() will react to the state of the promise.

Diagram: Promise() executor vs. then() method
(Code examples adapted from Jake Archibald's classic tutorial.)

This is a highly simplified view of how things work, leaving out many important details. But I think if one can keep a grip on a good overview of the intended purpose, it will help avoid confusion when one gets into the details.

A couple of selected details

The executor is called immediately

One important detail is that the executor function passed to the Promise() constructor is called immediately (before the constructor returns the promise); whereas the handler functions passed to the then() method will not be called till later (if ever).

Bergi mentioned this, but I wanted to restate it without using the terms a/synchronously, which can be confused if you're not reading carefully: The distinction between a function calling something asynchronously vs. being called asynchronously is easy to gloss over in communication.

resolve() is not onFulfill()

One more detail I'd like to emphasize, because it confused me for a while, is that the resolve() and reject() callbacks passed to the Promise() constructor's executor function are not the callbacks later passed to the then() method. This seems obvious in retrospect, but the apparent connection had me spinning in circles for too long. There is definitely a connection, but it's a loose, dynamic one.

Instead, the resolve() and reject() callbacks are functions supplied by the "system", and are passed to the executor function by the Promise constructor when you create a promise. When the resolve() function is called, system code is executed that potentially changes the state of the promise and eventually leads to an onFulfilled() callback being called asynchronously. Don't think of calling resolve() as being a tight wrapper for calling onFulfill()!

Why do I get a Promise executor has already been invoked with non-undefined arguments warning? (Node.js)

The problem is that this.then() constructs a new promise, following the contract of the Promise constructor which you have subclassed. To do so, it calls your Stream constructor with an executor that will use the passed resolver functions to resolve the new promise with the results from the then callbacks. This executor is expected to be called back only once - however your Stream does call it multiple times, once immediately and then during the resolve call.

Of the various promises constructed by your stream.map(console.log); call that never are handled anywhere, some appear to get rejected - rightfully if you ask me.

A Stream may consist of recursively chained promises1, but a stream is not a Promise. Do not use subclassing!

1: See this or that (also here) for examples. Notice that this linked-list like concept has been superseded by asynchronous iterators (blog post) now which have a stateful next() method. You will also want to have a look at What is the difference between async generators and Observables?.

Where does Promise executor callback live when asynchronous code is being run?

If that is the case, above code snippet's executor function has asynchronous code of making API call - will that also hang on to the main thread till API returns data.

No, it won't hang anything. request.send() is asynchronous and non-blocking. When you call request.send() it initiates the sending of the request (turns it over to the OS) and then immediately returns. The promise executor function itself returns and then the main thread is free to do whatever else it wants to do.

Meanwhile, sometime later, the underlying TCP operation will cause an event to get inserted into the event queue. When that event gets processed by the main thread (when it's not doing anything else and this event gets its turn in the event queue), the request object will then generate either an onload or an onerror event and the corresponding listener will resolve or reject the promise. That will set in motion the promise calling it's .then() or .catch() handlers on a future tick.

Using request this way is absolutely no different inside a promise executor function as it is anywhere else in node.js. It initiates the asynchronous, non-blocking operation, you set up some listeners for callbacks and then the nodejs interpreter is free to do other things until sometime later when a completion event occurs and some callbacks get called.

Where does Promise executor callback live when asynchronous code is being run?

It's not super clear what you mean by "where does it live?". The promise executor function is just like any other function. It's called synchronously and when it returns the new Promise() constructor returns and there's a promise created that the calling code can use. Sometime later that promise will get resolved or rejected (usually). Part of initializing and setting up the promise is running of the promise executor function, but that's just one step in creating the promise. That function doesn't block if you happen to do something asynchronous in it.

Javascript Promise Callback (when it is called)

The promise executor function is called immediately by the promise constructor. That's how it works. The usual point of that executor function is to initiate your asynchronous operation and then later when that asynchronous operation completes, you call resolve() or reject().

Here's an example of putting the plain callback version of fs.readFile() in a promise wrapper:

function readFilePromise(filename, options) {
return new Promise((resolve, reject) => {
fs.readFile(filename, options, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
});
}

Usage:

 readFilePromise("myfile.txt").then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});

Note: This is just an example for illustration here. Nodejs now already has promisified versions of fs.readFile called fs.promises.readfile, but this structure can be used when you need to manually promisify other more complicated things that don't have their own promise interface yet.


For a real world example of promisifying something more complicated see the mapConcurrent() function here or the rateLimitMap() function here.



Related Topics



Leave a reply



Submit