如何将 Angular 承诺转换为 jquery 延迟对象 [英] How convert Angular promise to jquery deferred object

查看:29
本文介绍了如何将 Angular 承诺转换为 jquery 延迟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将来自我的模块/sdk 的承诺返回到非角度 javascript.例如,如果我返回对 jquery 的承诺,我可能应该发送 jquery 延迟对象.如何将 Angular 承诺转换为 jquery 承诺/延迟 obj.

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.

非常感谢任何建议.

推荐答案

免责声明:jQuery 承诺与其他库不兼容 - 全部.jQuery 不会自行吸收其他第三方承诺.另一方面,Angular $q 承诺 - 会,所以只要您有选择,就将 jQuery 承诺同化为 Angular 承诺,反之亦然.(jQuery 3.0 中的所有这些更改,如果您看到此免责声明并且 3.0 已经发布 - 请发表评论).

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).

将 jQuery 承诺转换为 Angular 承诺:

Converting a jQuery promise into an Angular promise:

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

将 jQuery 承诺转换为原生或 Bluebird 承诺:

Converting a jQuery promise to a native or Bluebird promise:

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

将 Promises/A+ 投诉承诺(如 $q Angular 承诺或 Bluebird 承诺或原生承诺)转换为 jQuery 承诺:

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

另外值得注意 - Angular promises 可以使用 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
});

这篇关于如何将 Angular 承诺转换为 jquery 延迟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆