How convert Angular promise to jquery deferred object

徘徊边缘 提交于 2020-01-11 04:43:06

问题


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
});


来源:https://stackoverflow.com/questions/24611078/how-convert-angular-promise-to-jquery-deferred-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!