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.
Related
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.
I have read this article which is based on famous Domenic Denicola's article. The first one says:
The problem with jQuery’s implementation (up until version 1.9) is
that it doesn’t respect the second part of the specification, “This
function should return a new promise…”, that is “then” doesn’t return
a new promise object when executing one of the handlers (either the
fullfillment, the rejection or the progress handler).
I have found these bugs corresponding to this problem:
http://bugs.jquery.com/ticket/14510
https://github.com/jquery/jquery/issues/1722
My question is: what is the current state of this issue? Both are opened, so the work is still in progress. But, using jquery 2, you can chain promises with .then. So: is still jQuery.Promises implementation broken? Did anything change since version 1.9?
Update: As of jQuery 3.0 the answer is yes. jQuery promises are Promises/A+ compatible and can be safely used.
jQuery promises do not currently adhere to the Promises/A+ specification and thus have some issues and Domenic's article is still valid.
That said active work is being done and jQuery promises will finally be Promises/A+ compliant in the next version. It's still work in progress here is the relevant pull request and here. The last bit of work on it was two days ago.
Exciting times indeed.
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
I really like the idea of jQuery's deferred/promise pattern or paradigm but sometimes I have trouble wrapping my aging brain around the finer points or specific implementation details.
In fact recently I've found that the deferred/promise pattern/paradigm seems to predate jQuery and is also in at least these other JavaScript libraries/frameworks:
Deferred github
Q homepage
task.js homepage
when.js github
wire.js github, presentation
YUI gallery-deferred module
I've probably missed some, included stuff that's really part of one of the others, and made other mistakes in that list... Please edit it to correct it or leave comments.
Was the deferred/promise concept invented by "Q"? Was it invented with some other JavaScript library or framework? Or does it predate JavaScript completely?
If the whole idea has traditionally been part of functional programming, where was it first done and where can I read about the concept generally rather than these various different JavaScript implementations?
Or is functional programming entirely beside the point? Is the concept more related to concurrent programming than to functional programming?
According to Wikipedia: The term promise was proposed in 1976 by Daniel P. Friedman and David Wise, and Peter Hibbard called it eventual. A somewhat similar concept future was introduced in 1977 in a paper by Henry Baker and Carl Hewitt.
See:
Futures and promises history on Wikipedia:
The future and/or promise constructs were first implemented in
programming languages such as MultiLisp and Act 1. The use of logic
variables for communication in concurrent logic programming languages
was quite similar to futures. These started with Prolog with Freeze
and IC Prolog, and became a true concurrency primitive with Relational
Language, Concurrent Prolog, Guarded Horn Clauses (GHC), Parlog,
Vulcan, Janus, Mozart/Oz, Flow Java, and Alice ML. The
single-assignment I-var from dataflow programming languages,
originating in Id and included in Reppy's Concurrent ML, is much like
the concurrent logic variable.
The promise pipelining technique (using futures to overcome latency)
was invented by Barbara Liskov and Liuba Shrira in 1988,[12] and
independently by Mark S. Miller, Dean Tribble and Rob Jellinghaus in
the context of Project Xanadu circa 1989.[13]
The term promise was coined by Liskov and Shrira, although they
referred to the pipelining mechanism by the name call-stream, which is
now rarely used.
[...]
I think in JavaScript deferred/promise concept first appeared in Dojo (inspired by Python's Twisted) then in jQuery.
The notable moment is work of CommonJS group which put a lot effort to "standarize" promises for JavaScript, see A, B and D proposals, on that basis Kris Kowal's Q (I guess currently most popular implementation) evolved.
Deferred (I'm the author) is later implementation, it was initially inspired by Q, its goal is to make promises feel natural in JavaScript, and also to make transition from Node.js callback style easy.
But yes as #rsp wrote, promises are much older concept than JavaScript itself :)