How to cast jQuery $.ajax calls to Bluebird promises without the deferred anit-pattern

浪子不回头ぞ 提交于 2019-12-03 10:51:10
Benjamin Gruenbaum

You can call Promise.resolve on a jQuery thenable and have Bluebird assimilate it:

var res = Promise.resolve($.get(...)); // res is a bluebird Promise

You can also return jQuery promises directly inside a Bluebird chain and have it assimilate it.

myBluebirdApi().then(function(){
    return $.get(...);
}).then(function(result){
    // The jQuery thenable was assimilated
});

Your code below is close, but you don't need to catch TimeoutError since jQuery ajax won't throw those. As for catching cancellation error. This is best practice anyway for what you're doing if you ever expect to need to cancel the request.

Flimm

To convert a thenable to a Bluebird promise, you can use can call Promise.resolve like this:

var promise = Promise.resolve($.getJSON(...));

Bonus section:

Most JQuery AJAX functions are thenable, but for your information, if you want to convert a function that expects a callback to a promise, you can use Promise.fromNode. The callback will be called with the arguments err, result as is convention in the Node.js world:

var promise = Promise.fromNode(function (callback) { request(url, callback); });

If the callback doesn't expect a potential error for its first argument, you can work around that:

var promise = Promise.fromNode(function (callback) {
  FB.api(url, function(response) { callback(response ? response.error : "no response", response); });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!