do jQuery promises conform Promises/A+ - javascript

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.

Related

What does the "A+" stand for in "Promise/A+"?

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.

return deferred or deferred.promise() [duplicate]

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

How to retrieve native function code after it was redefined by third-party js?

I'm writing a userscript for tumblr that makes ajax calls to its API over an array of data and I need the responses to come in the order the data was in the array. I was advised to use Promises for that as the article shows (http://www.html5rocks.com/en/tutorials/es6/promises/#toc-parallelism-sequencing).
It works on individual tumblr blog pages, but not on the dashboard, where native implementation of Promise is overwritten by their index.js. As the result, their Promise lacks .resolve() ability and my code doesn't work.
Can I still find a way to use the native Promise or do I have to seek other ways? I'd prefer to stick with Promises to avoid having different code for a single use case. Alternatively, I would have to use jQuery for same functionality and I don't really know how.
Right now I'm solving this by force-loading of Promise polyfill from GitHub, but this doesn't feel right.

Differences in using Q vs When promise library for javascript [duplicate]

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

Implement promises pattern

I have a function that called with other objects and when my application is loaded, get parameter and the function should wait for call with all of object and then execute so with promises pattern i can ensure all object is loaded but i don't know about count of object and i don't want set timeout for loading.I don't talk about specific technology such as jquery and need algorithm.
Pseudo Code:
function loadWidget(id){
list.push(id);
//here I should ensure all Widget is loaded
}
in other application i call
app.loadWidget.add(widget1.id);
.
.
.
app.loadWidget.add(widget2.id);
If you don't want ready solutions and instead you want to implement all of the algorithms yourself then read the papers referenced in the Wikipedia article: Futures and promises and the specs for Promises/A and Promises/A+.
And to make sure that you're doing it right, read You're Missing the Point of Promises by Domenic Denicola and see the Compliances tests for Promises/A+.
If, on the other hand, you decide that it is not worth it to reinvent the wheel (unless it is for education - in which case by all means reinvent as many wheels as possible) then take a look at RSVP.js, a lightweight library that provides tools for organizing asynchronous code. RSVP.js is used for example by Ember.js.

Categories

Resources