Thenable Promise Protocol
In JavaScript today, any object with a then method is a promise, as far as
the language is concerned.
Promise.resolve will call it, and a promise made by one library can wait on
a promise made by another.
That idea was planted by Kris Zyp on the CommonJS mailing list in 2009.
I spent most of a year arguing against it, and then built my library, Q, to
accept and produce thenables anyway.
What turned me was not an argument but a bug in Q.
This is the story of how a handful of us, with a handful of incompatible
promise libraries, found our way to one interoperable method, and what we
argued about along the way.
The record is the CommonJS list, which was first named ServerJS, and the promise pages of the CommonJS wiki, which survive in the Internet Archive.
A Deferred and a Q #
On March 24, 2009, Kris Zyp opened the "Promise API Proposal" thread:
I promised to propose a promise API (sorry for the pun), so here it is. If I started from scratch, my personal preference would probably be to spell it "Future". But, I strongly believe in following prior implementations, and I am pretty sure that Dojo's Deferred API would be the most widely used promise API in JavaScript.
His proposal was a Deferred with callback, errback and progress for
the producer, addCallbacks(callback, errback, progressback) for the
consumer, a cancel, and an optional, blocking wait.
Mark S. Miller later
traced
the lineage: Dojo's and MochiKit's Deferreds came from Twisted's, and
Twisted's were an adaptation of E's promises.
(In a message Mark forwarded to the thread, Brian Warner recalled that
Glyph Lefkowitz, who came up with Twisted's Deferreds, had been less
directly inspired by E than that.)
Tyler Close
answered
with the case for promises as E and his own Waterken ref_send library had
them: a Q object with Q.when(promise, fulfilled, rejected), Q.get,
Q.post, and Q.defer(), which separates a promise from the power to
resolve it.
He warned that "this kind of API tends to be very contagious. Once one module
adopts it, it spreads to its public interface and so to the working's of
other libraries."
That warning turned out to be the whole problem.
By May 30, Kris Zyp had revised his proposal, and the revision held the seed of everything that followed:
One of the key changes proposed here is that the interface only defines how to interact with an instantiated promise, but does not dictate how the promise is fulfilled. Thus, this interface could be implemented by various implementors that have their own means of fulfilling the promise, which often may be internal (and it would be insecure and dangerous to expose).
He added that "a 'Q' API implementation can easily utilize this promise API for the promises that it passes around to the Q functions." A promise would be defined by what a consumer can do with it, and anyone could make one.
The name #
That same weekend, I
announced
that I had ported Tyler's ref_send, by way of Caja's port, to Narwhal as a
module named promise.
I confessed that I did not yet feel qualified to argue about promises, but
said
that on a quick glance I preferred "when" over "addCallbacks".
Kris Zyp
replied:
However, if you like four letter words, wouldn't "then" make more sense when used as a method name on a promise? "when" works grammatically as a static function where the promise comes after the function name (as in Q), but when the function name comes after the promise, it seems like "then" reads better.
That is where then comes from.
I held out
for when, on the grounds that Q.when(promise, observer) and
promise.when(observer) could mean the same thing, as eq(a, b) and
a.eq(b) do.
I lost, and English won.
And it is a good thing English won.
Duck typing in JavaScript obliges a static function and its dual method to
have distinct names, lest a constructor be confused for an instance.
Had the method been when, Q itself, a function with a when, would look
like a promise to any code that recognizes a promise by its method.
You can see the same thing in JSON.stringify and its relationship to
toJSON.
JSON.stringify calls a value's toJSON method when it has one.
JavaScript has no JSON.toJSON, but suppose the static had been named that,
with the static and the method meaning the same thing, as Q.when and
promise.when would have:
// Hypothetical: JavaScript has no JSON.toJSON.
const HypotheticalJSON = {
toJSON(value = this) {
if (typeof value?.toJSON === "function") {
return HypotheticalJSON.toJSON(value.toJSON());
}
return JSON.stringify(value);
},
};
HypotheticalJSON.toJSON({ toJSON: () => [1, 2] }); // "[1,2]"
HypotheticalJSON.toJSON(HypotheticalJSON);
// RangeError: Maximum call stack size exceeded
The namespace answers to its own duck type, and serializing it recurses into
itself.
The real JSON.stringify(JSON) gives "{}".
All three behave as shown in Node 26.
As much as I dislike the name stringify, I prefer the distinction over
cyclic recursion on JSON.toJSON.
One method #
In October, Charles Jolley, building a module loader for SproutCore, asked the list what a CommonJS promise actually was. Kris Zyp answered that, to work with both the promise proposal and the Q functions, "you simply need to return an object with a 'then' property with a function which takes a success callback and an error callback," and then, more plainly, that "then(successHandler, errorHandler) is the only required method on a Promise object."
Kris Zyp, in the same message, also raised the question at the heart of interoperation: how would you tell a promise from any other value?
My original intent (and the promise impl I did for narwhal) was that one could test an object to see if it was a promise with: promise instanceof require("promise").Promise But, I am not sure if we really have any discussed that at all on CommonJS, and should probably be decided. For JSGI 0.3, it sounded like the only requirement for a promise was the presence of a "then" property that was a function.
Tom Robinson, who had just added asynchronous responses to Jack, answered
for JSGI in the
next message:
"For JSGI, at least, I do prefer the duck typing approach of checking for a
'then' function."
In January 2010, Kris Zyp
suggested
stripping the proposal's get and call methods, "leaving only the then()
function."
In February, I suggested that his proposal, which had been sitting on the wiki's root page for promises, move to its own page, Promises/A, beside the others. The page as the Wayback Machine captured it in 2010 reads:
This API does not define how promises are created, but only defines the necessary interface that a promise must provide for promise consumers to interact with it. Implementors are free to define how promises are generated.
A promise is defined as an object that has a function as the value for the property 'then':
then(fulfilledHandler, errorHandler, progressHandler)
then returned a new promise for the handler's result, so that promise
operations could be chained.
The wiki's
index of proposals
came to list it as "Promises/A by Kris Zyp — 'Thenables'".
The opaque camp #
I came to doubt it.
In that February letter, addressed to Tyler Close, I set out what I had
learned from his code.
Q.when(promise, ok, error) provides two invariants: that either ok or
error will be called exactly once, and that they will be called in a
future turn of the event loop.
Calling promise.then(ok, error) directly gives both up, because it hands
your callbacks to the promise, and a promise you did not make can call them
now, later, twice, or both.
The important point to glean from this is that the anti-pattern is in the usage of the Promise API, not in the implementation of the Promise API or Q API. … The anti-pattern is furthermore virulent because it is syntactically compelling.
I did not yet have a conclusion: "There merely appears to be a tension
here."
Tyler
agreed
that directly invoking methods on a promise is an anti-pattern, and said the
oddness of ref_send's promises, which were functions you called with an
operation name, was deliberate: "I want it to feel odd to write unsafe
code."
Kris Zyp
disagreed.
Object freezing had arrived in the server engines, so a promise could be an
ordinary object and still be protected from tampering, and:
These are mainly usability concerns, and the reality is that people really are mainly interacting with trusted code, and many want to use infix style promise interaction. You can try to convince everyone one otherwise, but I don't think CommonJS is in a position to make such opinionated APIs.
The other thing then could not do was carry any message but then.
Tyler's promises accepted GET, POST and the rest, so you could send a
message to a promise for a remote object before it resolved.
As I
put it
in March, "the 'then' protocol would not support catch-alls for erroneous,
unsupported, or proxied messages other than 'then', like 'post'."
That month I wrote that "'.then' has to go," and posted Promises/B, the Q API as a specification, which opens:
A promise is an opaque object:
- How to send messages to a promise object is beyond the scope of this specification.
- How to detect whether a value is a promise object is beyond the scope of this specification.
Kris Zyp
wrote back,
"Sorry, but I am -1 to opaque promise objects."
He had already
pointed out
that the core of Promises/A, the then method, had stood in basically the
same form for almost a year, with implementations in Narwhal, node-promise
and Dojo.
By May, I had given the camps their names: "having myself converted from the Thenable camp to the Opaque Promise camp, I probably won't be converting back." I proposed that we reserve one module name for each and take the conflict "into the market of adoption." Hannes Wallnoefer, who had just written a Promises/A module for RingoJS, wrote, "Whether it's duck typed then or opaque when is just an implementation detail." And Kris Zyp made the argument that, in the end, carried the day:
I would point out the elegance of Promise/A is that we don't even need a CommonJS defined, platform provided, system module for promises. … It is my belief that CommonJS should attempt to achieve the goal of interoperability while defining as little as possible, giving the maximum amount of freedom for innovation and invention for implementers, and allowing independent evolution and versioning. I believe this has been demonstrated by the fact that independent interoperable promises implementations have been produced by myself, Hannes, and Kowal's "events" module also produced compatible promises, and we are successfully using promises on Node right now.
What else we disagreed about #
The fight over then was the loud one.
Under it ran three quieter disagreements, and the specifications that came
after settled each of them.
Synchronous resolution. Promises/A left open whether handlers run at once or in a later turn. Its one open issue was "Should calls to the callback handlers be put on the event queue or executed immediately? - Currently unspecified, and I don't know for sure what is best." Promises/B required that a callback "must not be called before when returns." Nuutti Kotivuori, who came to the list in October 2010 with a proposal of his own, asked why promises should wait for a future turn at all: "if a function a calls a function b, the call isn't resolved in a 'future turn' - so why should promises be different?"
Errors.
Promises/A said that if a handler throws, the promise then returns is
moved to the failed state.
Nuutti's first complaint about Promises/B, as he read it, was that
"exceptions thrown by callbacks are not handled as a rejection to the future
promise," and "for me, a promise is like a function call - it either
generates a value, or an exception."
Kris Zyp
replied
that nearly all of what Nuutti wanted matched Promises/A already, and
defended its two handlers against Nuutti's one, because "being able to omit
the error callback is important for easing error delegation without having
to manually rethrow (like a function without a try/catch block)."
Progress.
Promises/A's then took a third, optional progressHandler, which an
implementation was free never to call.
Q had nothing of the kind, as Irakli Gozalishvili
noted
in November 2010.
The One True Promise Library #
The argument that finally moved me was not about safety or style. It was about packages.
In November 2010, Irakli tried once more to unify the two proposals. Nathan Stott, who used Bogart, which was built on Kris Zyp's promises, and wanted Jaque, which was built on mine, reported what happened when he tried both:
It was my impression, until I actually tried it, that as long as I avoided using '.then' and only used 'Q.when' that the promise implementation wouldn't matter. This is not the case.
Dean Landolt put the difference plainly:
Promises/A solves interop nicely but at the cost of opacity. Promises/B is arguably more correct but requires you to use The One True Promise Library. Oh, and you have to make sure your code gets the same One True Promise Library as the libraries you're exchanging promises with. To date this is an unsolved problem.
Irakli
hoped
that npm would see to it that every package got the same library.
Dean
answered,
"Quite the opposite AFAICT. The npm shims could lead to multiple versions of
a promise lib being installed and used at any given time."
An instanceof check fails between two copies of the same library, and I
learned that from my own.
Every version of Q I had published to npm, from the
first
in September 2010, recognized its own promises with instanceof:
function isPromise(object) {
return object instanceof Promise;
};
That Q met an eval twin of
itself: a second copy of the same module, evaluated on its own, with its own
Promise constructor, so that each copy took the other's promises for plain
values.
The twin came from npm's failure to deduplicate patch versions of Q in some
degenerate dependency trees.
The npm of the time installed every version of a package side by side and
linked
each package to the versions of its own dependencies, and two packages could
each bring their own Q.
That forced the issue of duck typing.
I needed Q to recognize, or at least adopt, the promises of its eval twins.
On November 29, I
conceded
on the list that "this is probably the most compelling reason to go with a
duck-type under the hood," and on December 3 I
committed
the change to Q, with this entry in its change log:
"Changed promises into a duck-type such that multiple instances of the Q
module can exchange promise objects."
Promise-sendables #
So I went to a duck-type, but not to then.
The duck in that December commit was a method named, unlikely enough,
"I look like a promise, I quack like a promise."
An hour later, I
proposed
on the list that a promise be any object with a method of an unlikely name
that receives every message, and in January 2011 I
drafted
Promises/D, "promiseSendables".
Its
rationale
is Nathan's problem stated as a requirement:
It is necessary to use a duck-method for multiple instances of the promise module to interoperate in the same run-time, which is possible when using package managers like Isaac Schlueter's NPM for Node and different packages depend on different specific versions of the promise module.
Q's duck
became
promiseSend, and the duck-typed Q went out as version 0.2.5 on January 10.
That let copies of Q, and other implementations of Promises/B, work with
each other.
It did not let them work with a thenable, which has no promiseSend.
Assimilation #
Later that month, Kevin Smith asked me why Q should not simply have a then
method.
I answered
with the hazard, as a bank account:
var moneyInTheBank = balance;
suspicious().then(function () {
moneyInTheBank -= transactionAmount;
return cryptographicWithdrawl(transactionAmount);
});
"Meanwhile in suspicious land":
function suspicious() {
return {"then": function (resolved) {
resolved(); resolved(); resolved();
setInterval(resolved, 1000);
})
}
The next day, I
pushed
a branch:
"This variation of the Q implementation both assimilates and provides
thenables. … So, clearly we can do the thing. The question remains whether
we should."
Kevin asked what guarantees survive when a questionable thenable is
assimilated, and I
answered:
"All of the guarantees of 'when' hold."
My worry was that people would call then directly anyway, because it is
so much more convenient.
Kevin's
reply
deserves the last word on that:
"it's proven time and again that if you don't give users the right way to do
something dangerous, they do it the wrong way all the same."
In fairness, it was my roommate at the time, Dirk Neumann, who nudged me to
the practical position.
I had
named him
on the list that November, among the people I was working with to port
promise utilities.
On January 31, I released Q 0.2.6, and its entry in the change log begins:
Thenables (objects with a "then" method) are accepted and provided, bringing this implementation of Q into conformance with Promises/A, B, and D.
Once Q recognized promises by their shape and not by their constructor, it
could adopt the promises of other libraries as readily as those of its eval
twins.
That included jQuery's.
jQuery 1.5, dated the same day,
introduced its Deferred, whose then did not even fully honor the thenable
contract.
It returned this, as was the norm for jQuery pipelines, rather than a new
promise for the handler's result:
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
It stayed that way until jQuery 1.8, in August 2012, whose
change log lists
"Make Deferred.then == Deferred.pipe like Promise/A".
The logic for adopting a thenable does not require a compliant return value.
Q called the foreign then once, with resolving functions of its own, and
ignored whatever it returned, as the code stood by
March:
// assimilate thenables, CommonJS/Promises/A
if (object && typeof object.then === "function") {
return Promise({}, function fallback(op, rejected) {
if (op !== "when") {
return reject("Operation " + op + " not supported by thenable promises");
} else {
var result = defer();
object.then(result.resolve, result.reject);
return result.promise;
}
});
}
That was the resolution of the whole argument, though it took me a while to see it. A thenable is a fine thing to receive, so long as the library you trust takes it at the door. It is only a hazard to hand your own callbacks to it. As I later put it in A General Theory of Reactivity, "using a promise library in your control, you can coerce any foreign promise to a promise with an interface and behavior you can rely on to protect your scope invariants."
By May 2011, when I wrote How to design a JavaScript promise
library, the library that essay builds still produced and
consumed thenables, "routing their message through 'promiseSend'
internally," and I wrote of duck-typing on then that "in practice, this is
not a problem, and the minor variations in 'thenable' implementations in the
wild are manageable."
By October, the wiki's Promises/A page
listed
Q as "thenable", beside Brian Cavalier's when.js and jQuery 1.5, which was
"said to be 'based on the CommonJS Promises/A design'."
After CommonJS #
Promises/A+ took Kris Zyp's definition and made it precise.
Version 1.0,
of December 2012, "clarifies the behavioral clauses of the Promises/A
proposal," defines a promise as "an object or function that defines a then
method," requires that "then must return before onFulfilled or
onRejected is called," and gives then two arguments, with no progress
handler.
In March 2013, Domenic Denicola
added
a "Thenable Assimilation Procedure", which became the Promise Resolution
Procedure of version 1.1, in September 2013.
In the
current text:
This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant
thenmethod. It also allows Promises/A+ implementations to "assimilate" nonconformant implementations with reasonablethenmethods.
The procedure calls a thenable's then with resolving functions of its own,
and if they are called more than once, "the first call takes precedence, and
any further calls are ignored."
Those are the guarantees of Q.when, applied to every thenable.
ECMAScript 2015
put the same procedure in the language.
A promise's resolve function reads resolution.then, and if it is
callable, does not call it right away: it enqueues a
PromiseResolveThenableJob, which calls then in a later job with a fresh
pair of resolving functions.
Promise.resolve(x)
returns x itself only when it is a promise made by the same constructor,
and otherwise resolves a new promise with it, assimilating whatever thenable
it was given.
The collateral #
The language now adopts any thenable, from anywhere, and that is not free. There are numerous ways that thenable adoption is a blight.
A module namespace that exports a then function is a thenable, and dynamic
import adopts it.
A static import of this module works, but await import(…) hands the
namespace to its resolve function, which finds then and calls it with a
resolve function that this then never calls, so the import never settles:
// steps.js
export function first() {
return "first";
}
export function then(next) {
return next;
}
const steps = await import("./steps.js");
console.log(steps.first()); // never runs
Monkey-patching then onto Object.prototype makes every object a
thenable, and breaks everything that resolves a promise with an object:
Object.prototype.then = function (resolve) {
resolve("hijacked");
};
async function getUser() {
return { name: "Alice" };
}
console.log(await getUser()); // "hijacked"
Both behave as shown in Node 26. These are collateral.
So the language took both sides.
Kris Zyp's thenable is the interface: anything with a then method is a
promise, from any library, in any number of copies.
Tyler Close's discipline is the implementation: a foreign then is called
only by a promise you trust, in a later turn, with callbacks that count only
once.
I argued that we had to choose, and the answer was that the consumer's
library takes the thenable at the door.
I still consider thenables a blemish and a bug farm for JavaScript.
But features must get traction in the community before the language adopts
them, and I see no other course through history that would have led to
Promise landing first in JavaScript without the baggage of thenables.
Kris Zyp's seed is how promises got that traction, and the
choice is not the reason I lose sleep at night.
- Previous: Board Book Shop