10

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.

4

1 回答 1

21

免责声明: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(..));

将 Promises/A+ 投诉承诺(如 $q Angular 承诺或 Bluebird 承诺或原生承诺)转换为 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
});
于 2014-07-07T13:13:01.620 回答