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

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

问题描述

我想将我的模块/SDK中的promise返回到非角度javascript.例如,如果我向一个jQuery返回promise,则可能应该发送jquery延迟对象.如何将Angular promise转换为jquery promise/deferred 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.

任何建议都将不胜感激.

Any suggestions are much appreciated.

推荐答案

免责声明:jQuery承诺不能与其他库配合使用-在 all 处. jQuery不会自行吸收其他第三方的承诺.另一方面,Angular $ q promise-将会,因此,只要您有选择,就将jQuery promise吸收为Angular promise,反之亦然. (如果您看到此免责声明,并且3.0已经发布,则jQuery 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 Prom转换为本机或Bluebird Prom:

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

同样值得注意的是-角度承诺可以消耗jQuery承诺:

$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 Promise转换为jQuery延迟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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