【问题标题】:How convert Angular promise to jquery deferred object如何将 Angular 承诺转换为 jquery 延迟对象
【发布时间】:2014-08-27 23:08:26
【问题描述】:

我想将我的模块/sdk 中的 Promise 返回到非 Angular javascript。例如,如果我向 jquery 返回承诺,我应该可能会发送 jquery 延迟对象。如何将 Angular 承诺转换为 jquery 承诺/延迟 obj。

非常感谢任何建议。

【问题讨论】:

  • 为什么?有例子吗?
  • 例如,您可以使用 $q.when(thirdPartyPromise) 将任何第三方承诺转换为 $q/Q 承诺。但是应该有那个库来使用我的承诺。我不想强迫我的客户使用 Q 或 Angular,以便他可以重用我的承诺。如果我可以将它转换为他想要的兼容承诺,那么使用起来会更轻松。
  • 你应该考虑使用一个极简的promise库而不是jQuery promises,jQuery promises在错误处理上天生就有问题。
  • @phani Promises 在实现之间是designed to be interchangeable,你不会强迫你的客户做任何事情。 jQuery deferreds 不符合 Promise 规范,所以你不应该在 jQuery 之外使用它们。

标签: jquery angularjs promise jquery-deferred angular-promise


【解决方案1】:

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

将 jQuery 承诺转换为 Angular 承诺:

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

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

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

将诸如 $q Angular 承诺或 Bluebird 承诺或原生承诺之类的 Promises/A+ 投诉承诺转换为 jQuery 承诺:

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 Promise 可以使用 jQuery Promise

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

【讨论】:

  • 非常感谢本杰明的回答。
  • 你好,我有一个 signalR 承诺(SignalR 返回一个 Jquery 承诺), chunkPromise=proxy.server.myMethod(a,b) 但是当我做 $q.when(chunkPromise) 返回的对象是"d",只有 $$state 成员,而不是 $q 承诺。我做错了什么?
  • Jquery 3.0 已经发布;)
  • 谢谢@MarioLevrero!
猜你喜欢
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 2023-03-21
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
相关资源
最近更新 更多