-->

How convert Angular promise to jquery deferred obj

2019-02-16 20:02发布

问题:

I want to return promises from my module/sdk to non-angular javascript. For example if I'm returning promise to a jquery, I should be probably sending jquery deferred object. How can I convert an Angular promise to a jquery promise/deferred obj.

Any suggestions are much appreciated.

回答1:

Disclaimer: jQuery promises don't play nice with other libraries - at all. jQuery will not assimilate other third party promises on its own. Angular $q promises on the other hand - will, so whenever you have the choice, assimilate the jQuery promise into an Angular promise and not vice versa. (All this changes in jQuery 3.0, if you see this disclaimer and 3.0 has already been released - please leave a comment).

Converting a jQuery promise into an Angular promise:

var angularPromise = $q.when(jQueryPromise); // eg: $q.when($.get(...));

Converting a jQuery promise to a native or Bluebird promise:

var promise = Promise.resolve(jQueryPromise); // eg: Promise.resolve($.get(..));

Converting a Promises/A+ complaint promise like $q Angular promise or Bluebird promise or native promises into jQuery promises:

function convert(p){
    var d = $.Deferred();
    p.then(function(val){
       d.resolve(val);
    }, function(err){ 
       d.reject(err); 
    });
    return d.promise();
}

var jqPromise = convert($http.get(...)); // example usage

// you might be tempted to think you can easily do:
var jqPromise = $.when($http.get(...));
// however - this will will fail inconsistently due to differences between 
// jQuery and Angular promises

Also worth noting - Angular promises can consume jQuery promises:

$http.get(...).then(function(id){
    return $.get("http://..."+id); // will work, though pointless because $http.get
}).then(function(result){
     // contains result of $.get call here
});