What aspects of a promise library does the spec not cover? What kind of things vary between implementations?
Please illustrate with examples of actual differences (eg between Bluebird and Q).
Almost everything. The Promises/A+ spec is aimed for promise interoperability, it's built so promise libraries (and now, native promises) can talk to each other. The idea is for it to be possible to predict how a promise behaves and to define how promises are assimilated by other libraries.
Quoting the specification:
This specification details the behavior of the then method, providing an interoperable base which all Promises/A+ conformant promise implementations can be depended on to provide. As such, the specification should be considered very stable. Although the Promises/A+ organization may occasionally revise this specification with minor backward-compatible changes to address newly-discovered corner cases, we will integrate large or backward-incompatible only after careful consideration, discussion, and testing. Finally, the core Promises/A+ specification does not deal with how to create, fulfill, or reject promises, choosing instead to focus on providing an interoperable then method. Future work in companion specifications may touch on these subjects.
The following are not covered:
Creating a promise (that's the promise constructor spec).
Promise aggregation (although most implementations support .all).
Progression (that's the progression spec, which will soon be replaced imo).
Cancellation (that's the cancellation spec).
Unhandled rejection monitoring (there is no spec, but there is an inspection discussion).
Stack traces.
Bluebird and Q for example, are both completely Promises/A+ complaint but differ on a lot of these:
The next Q, v2 introduces estimation, where Bluebird intends to deprecate progression eventually in favor of something like C#'s IProgress.
Creating a promise is usually done with deferreds in Q (although it now offers a promise constructor variant), Bluebird encourages the promise constructor.
Bluebird has more robust and stronger promisification abilities, turning a whole callback API to promises in a single command. Q author Kris built Q-IO which manually promisifies the filesystem and http modules.
Bluebird allows scoped binding of this value via .bind, and promise array methods (.map,.reduce,.filter etc).
Q has primitives like asynchronous queues, and RPC via Q-connection in mind,
Bluebird is about 100 times faster, has better stack traces, and automatic unhandled rejection detection. It also consumes a lot less RAM memory per promise.
Here is another reference
Related
What does the "A+" stand for in "Promise/A+"? I tried looking online, but I keep getting programming examples or introductions to promises. Not really what I was looking for. As a note: I found the Promise/A+ from https://promisesaplus.com/
From the Promises/A+ spec
Historically, Promises/A+ clarifies the behavioral clauses of the earlier Promises/A proposal, extending it to cover de facto behaviors and omitting parts that are underspecified or problematic.
The A+ refers to the extension of the Promises/A spec.
So #wheaties helped me with finding the answer, if he posts an answer, I'll switch to accept his, in the meantime I'll post this.
So the A+ is just the proposal name for a promise implementation. Out of what I was able to find from what #wheaties said, I also found one more.
Promises/A, Promises/B, Promises/C, Promises/D, Promises/KISS
you can learn more about these from the common.js wiki http://wiki.commonjs.org/wiki/Promises
From promisesaplus.com:
An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled.
This specification details the behavior of the then method, providing an interoperable base which all Promises/A+ conformant promise implementations can be depended on to provide. As such, the specification should be considered very stable. Although the Promises/A+ organization may occasionally revise this specification with minor backward-compatible changes to address newly-discovered corner cases, we will integrate large or backward-incompatible changes only after careful consideration, discussion, and testing.
Historically, Promises/A+ clarifies the behavioral clauses of the earlier Promises/A proposal, extending it to cover de facto behaviors and omitting parts that are underspecified or problematic.
Finally, the core Promises/A+ specification does not deal with how to create, fulfill, or reject promises, choosing instead to focus on providing an interoperable then method. Future work in companion specifications may touch on these subjects.
I am checking out the "Promises/A+" Specification, but could not understand the following things:
On Section 1. Terminology,
1.1. "promise” is an object or function with a then method whose behavior conforms to this specification.
1.2. “thenable” is an object or function that defines a then method.
So What is the difference between the terms "thenable" and "promise"?
Also in Section 2.3. The Promise Resolution Procedure,
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x).
So my question is:
Why is it denoted within 2 opening and closing brackets? Is there any convention?
Thank you very much.
So What is the difference between the terms "thenable" and "promise"?
I think the section you've already cited does answer this very well:
A thenable is an object with a then method. Any object.
A promise is an object with a then method (i.e. a thenable) that conforms to the specification.
So far so simple. I think your actual question is: "Why are they distinguished?"
The problem is that by looking at an object you cannot decide whether it is a promise.
You might be able to tell that it is a promise because you can see that its then method is implemented by yourself or someone you trust - the promise library of your choice usually. You would be able to "see" that because the object does inherit from your promise prototype, or you can even compare the method being (referentially) identical to the function you've defined. Or any other inspection method that is sufficient for you.
You might be able to tell that it is not a promise because it has no then method.
But what do you do with an object that implements then, but is not known to be a promise? It's a thenable, and will be handled as such.
The Promises/A+ specification aims for interoperability between promise implementations, and uses the existence of a .then() method for duck typing. It does specify an exact algorithm on how to treat such thenables (that might be promises or at least have similar behaviour) so that you can create an actual, trusted ("known") promise from them.
Why is it denoted within 2 opening and closing brackets? Is there any convention?
Yes, the ECMAScript specifications use this syntax for internal methods and properties:
The names of internal properties are enclosed in double square brackets [[ ]].
Those properties do not actually need to exist, they're purely used to describe what should happen - an implementation must act as if it used them. They are totally abstract operations though.
This is a smart attempt to make it easier for promises to be interoperable between different libraries.
The spec uses the term thenable in just a few places. This one is the most important (empasis mine):
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.
This will make implementors do a check like:
if (typeof(x.then) === 'function') {
// adopt the state of x
} else {
// fulfill promise with value x
}
If the spec instead said "if x is a promise, then...", how would the implementor know whether x is a promise or not? There's no practical way to make sure if x complies with the Promise spec just by inspecting it.
An implementor (say, library FooPromises might do something like
if (x instanceof FooPromises.Promise) {
// adopt the state of x
} else {
// fulfill promise with value x
}
and it would effectively reject any promises coming from different implementations.
Instead, by using a super-simple definition of thenable in this condition that implementors can easily verify, it's trivial to make this check and you make it possible for implementations to play nice with each other.
For you second question, I'm not sure but my idea would be that a notation [[Resolve]](promise, x) emphasises that it's an abstract operation. If they dropped the brackets and just said Resolve(promise, x), it would somehow imply that implementors should make a real function named Resolve and expose it.
This is not needed - Resolve is not part of the promises' interface; it's just a part of their behaviour that was important enough that it was given a name and a separate section in the docs.
What are the differences between Deferreds, Promises and Futures?
Is there a generally approved theory behind all these three?
These answers, including the selected answer, are good for introducing promises
conceptually, but lacking in specifics of what exactly the differences are in
the terminology that arises when using libraries implementing them (and there
are important differences).
Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):
Deferred: Never described in popular references,
1
2
3
4
but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject).
5
6
7
Sometimes deferreds are also promises (implementing then),
5
6
other times it's seen as more pure to have the Deferred only
capable of resolution, and forcing the user to access the promise for
using then.
7
Promise: The most all-encompasing word for the strategy under discussion.
A proxy object storing the result of a target function whose
synchronicity we would like to abstract, plus exposing a then function
accepting another target function and returning a new promise.
2
Example from CommonJS:
> asyncComputeTheAnswerToEverything()
.then(addTwo)
.then(printResult);
44
Always described in popular references, although never specified as to
whose responsibility resolution falls to.
1
2
3
4
Always present in popular implementations, and never given
resolution abilites.
5
6
7
Future: a seemingly deprecated term found in some popular references
1
and at least one popular implementation,
8
but seemingly being phased out of discussion in preference for the term
'promise'
3
and not always mentioned in popular introductions to the topic.
9
However, at least one library uses the term generically for abstracting
synchronicity and error handling, while not providing then functionality.
10
It's unclear if avoiding the term 'promise' was intentional, but probably a
good choice since promises are built around 'thenables.'
2
References
Wikipedia on Promises & Futures
Promises/A+ spec
DOM Standard on Promises
DOM Standard Promises Spec WIP
DOJO Toolkit Deferreds
jQuery Deferreds
Q
FutureJS
Functional Javascript section on Promises
Futures in AngularJS Integration Testing
Misc potentially confusing things
Difference between Promises/A and Promises/A+
(TL;DR, Promises/A+ mostly resolves ambiguities in Promises/A)
In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
If you're interested in the minutiae, then examine Promises/A+.
So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from #jfriend00:
Rather than directly passing callbacks to functions, something which
can lead to tightly coupled interfaces, using promises allows one to
separate concerns for code that is synchronous or asynchronous.
Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.
Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):
/* assume getScript has signature like: function (path, callback, context)
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);
// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};
function ourAwesomeScript() {
console.log("CodeMirror is awesome, but I'm too impatient.");
};
});
To the promises formulated version (again, apologies, I'm not up to date on jQuery):
/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log("CodeMirror is awesome, but I'm too impatient.");
});
});
Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.
What really made it all click for me was this presentation by Domenic Denicola.
In a github gist, he gave the description I like most, it's very concise:
The point of promises is to give us back functional composition and error bubbling in the async world.
In other word, promises are a way that lets us write asynchronous code that is almost as easy to write as if it was synchronous.
Consider this example, with promises:
getTweetsFor("domenic") // promise-returning async function
.then(function (tweets) {
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
})
.then(doHttpRequest) // promise-returning async function
.then(
function (responseBody) {
console.log("Most recent link text:", responseBody);
},
function (error) {
console.error("Error with the twitterverse:", error);
}
);
It works as if you were writing this synchronous code:
try {
var tweets = getTweetsFor("domenic"); // blocking
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
var responseBody = doHttpRequest(expandUrlUsingTwitterApi(mostRecentShortUrl)); // blocking x 2
console.log("Most recent link text:", responseBody);
} catch (error) {
console.error("Error with the twitterverse: ", error);
}
(If this still sounds complicated, watch that presentation!)
Regarding Deferred, it's a way to .resolve() or .reject() promises. In the Promises/B spec, it is called .defer(). In jQuery, it's $.Deferred().
Please note that, as far as I know, the Promise implementation in jQuery is broken (see that gist), at least as of jQuery 1.8.2.
It supposedly implements Promises/A thenables, but you don't get the correct error handling you should, in the sense that the whole "async try/catch" functionality won't work.
Which is a pity, because having a "try/catch" with async code is utterly cool.
If you are going to use Promises (you should try them out with your own code!), use Kris Kowal's Q. The jQuery version is just some callback aggregator for writing cleaner jQuery code, but misses the point.
Regarding Future, I have no idea, I haven't seen that in any API.
Edit: Domenic Denicola's youtube talk on Promises from #Farm's comment below.
A quote from Michael Jackson (yes, Michael Jackson) from the video:
I want you to burn this phrase in your mind:
A promise is an asynchronous value.
This is an excellent description: a promise is like a variable from the future - a first-class reference to something that, at some point, will exist (or happen).
A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).
If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.
If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.
Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.
A promise represents a value that is not yet known
A deferred represents work that is not yet finished
A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.
Reference
http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics
I am checking out the "Promises/A+" Specification, but could not understand the following things:
On Section 1. Terminology,
1.1. "promise” is an object or function with a then method whose behavior conforms to this specification.
1.2. “thenable” is an object or function that defines a then method.
So What is the difference between the terms "thenable" and "promise"?
Also in Section 2.3. The Promise Resolution Procedure,
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x).
So my question is:
Why is it denoted within 2 opening and closing brackets? Is there any convention?
Thank you very much.
So What is the difference between the terms "thenable" and "promise"?
I think the section you've already cited does answer this very well:
A thenable is an object with a then method. Any object.
A promise is an object with a then method (i.e. a thenable) that conforms to the specification.
So far so simple. I think your actual question is: "Why are they distinguished?"
The problem is that by looking at an object you cannot decide whether it is a promise.
You might be able to tell that it is a promise because you can see that its then method is implemented by yourself or someone you trust - the promise library of your choice usually. You would be able to "see" that because the object does inherit from your promise prototype, or you can even compare the method being (referentially) identical to the function you've defined. Or any other inspection method that is sufficient for you.
You might be able to tell that it is not a promise because it has no then method.
But what do you do with an object that implements then, but is not known to be a promise? It's a thenable, and will be handled as such.
The Promises/A+ specification aims for interoperability between promise implementations, and uses the existence of a .then() method for duck typing. It does specify an exact algorithm on how to treat such thenables (that might be promises or at least have similar behaviour) so that you can create an actual, trusted ("known") promise from them.
Why is it denoted within 2 opening and closing brackets? Is there any convention?
Yes, the ECMAScript specifications use this syntax for internal methods and properties:
The names of internal properties are enclosed in double square brackets [[ ]].
Those properties do not actually need to exist, they're purely used to describe what should happen - an implementation must act as if it used them. They are totally abstract operations though.
This is a smart attempt to make it easier for promises to be interoperable between different libraries.
The spec uses the term thenable in just a few places. This one is the most important (empasis mine):
The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.
This will make implementors do a check like:
if (typeof(x.then) === 'function') {
// adopt the state of x
} else {
// fulfill promise with value x
}
If the spec instead said "if x is a promise, then...", how would the implementor know whether x is a promise or not? There's no practical way to make sure if x complies with the Promise spec just by inspecting it.
An implementor (say, library FooPromises might do something like
if (x instanceof FooPromises.Promise) {
// adopt the state of x
} else {
// fulfill promise with value x
}
and it would effectively reject any promises coming from different implementations.
Instead, by using a super-simple definition of thenable in this condition that implementors can easily verify, it's trivial to make this check and you make it possible for implementations to play nice with each other.
For you second question, I'm not sure but my idea would be that a notation [[Resolve]](promise, x) emphasises that it's an abstract operation. If they dropped the brackets and just said Resolve(promise, x), it would somehow imply that implementors should make a real function named Resolve and expose it.
This is not needed - Resolve is not part of the promises' interface; it's just a part of their behaviour that was important enough that it was given a name and a separate section in the docs.
are there any javascript libraries which provide promises and futures syntactically similar to that of C++ ones. basically we want to use them in webworkers, I dont want a callback interface. I want the webworker to block on a future and continue when the UI thread sets the value of the future. i have looked at every possible promise and future library but every thing expects a callback, our code is already a mess and we dont want to further complicate it.
http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses-promise.js
Implementation of promises for SES/ES5. Exports Q to the global scope.
Mostly taken from the ref_send implementation by Tyler Close, with the addition of a trademark table to support promises for functions.
Btw, Mark Miller is working on codifying JavaScript's concurrency model and adding eventual send semantics with syntactic sugar for a future version of the language. From http://wiki.ecmascript.org/doku.php?id=strawman:concurrency
Reality: Codifying and formalizing JavaScript’s de-facto concurrency model as a de-jure model.
Promises: A way to (Q(p).post(), Q(p).get()) Make asynchronous requests of objects that may not be synchronously reachable, such as remote objects. (Q(p).when()) Ease the burden of local event loop programming, by reifying the ability to register a callback as a first class value. (Q.async, yield:) for implicit registration of shallow continuations on promises.
Syntactic sugar. The infix “!” operator: An eventual analog of “.“, for making eventual requests look more like immediate requests.
(Q.makePromise()) A promise extension mechanism, so that promise handlers can turn local promise operations into remote messages.
Transport independence: Using remote object messaging as a symmetric abstraction layer, hiding the annoying differences among the various transports listed above as well as server-to-server TCP and UDP transports.
(Vat()) An event-loop spawning mechanism for spawning new event loops that run concurrently with the event loop which spawned it.
Worker independence: Using Vat API as an abstraction layer around worker spawning on the browser or process spawning on the server.
(Vat.evalLater(), where()) Using JavaScript itself as mobile code, so event loops can safely inject new behavior into other event loops
Symmetric Mobile Code: Generalizes from the current use of JavaScript as mobile code sent only from server and only to browsers.
Async-PGAS: Provides a distributed analog to the expressiveness of The Asynchronous Partitioned Global Address Space Model.