I am using jQuery Deferred for some asynchronous event handling. More or less due to theoretical purity of my code I want to be Promise/A+ compliant. (The more practical reason is that later I can update my code to use native Promise implementations as soon as all major browsers support them.)
However, I use a particular feature of jQuery's Deferred that sets it apart from Promise/A+ and I do not know how to work around it. Hence, I would like to know how I can solve the following problem in a Promise/A+ compliant manner.
The core of the problem is that I already need the Promise object in order to bind a handler to it before I know the exact executor of the promise, because the executor depends on some parameters that will become known later. With jQuery's Deferred this is not a problem because I can create an "empty" Deferred first, bind some handler to it and then attach the executor to it. With Promise/A+ the executator must be immediately given as the parameter of the constructor and will be immediately executed even before the constructor of the Promise returns.
At the moment I have something like this:
// Create "empty" deferred
deferred = jQuery.Deferred();
// Attach one or more handlers
deferred.then(
function onFullfilled( value ) {
// do something
}
);
// Somewhere at some totally different part of code after the particular
// URL has become known
jQuery.ajax( "www.myhost.com/my/url", {
error: function( jqXHR ) {
deferred.reject( jqXHR );
},
success: function( data, status, jqXHR ) {
deferred.resolve( jqXHR );
}
});
With Promise/A+ I have to do something like this but I can't:
// Create promise
promise = new Promise( function( resolve, reject ) {
// Error, ups: I do not know the URL yet
jQuery.ajax( "www.myhost.com/my/url", {
error: function( jqXHR ) {
resolve( jqXHR );
},
success: function( data, status, jqXHR ) {
reject( jqXHR );
}
});
);
// Attach one or more handlers
promise.then(
function onFullfilled( value ) {
// do something
}
);
Thanks you!
http://www.html5rocks.com/en/tutorials/es6/promises/