Jeff Jeff - 2 months ago 24
Javascript Question

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

Right now I use promise.deferred in a core file. This allows me to resolve promises at a central location. I've been reading that I may be using an anti-pattern and I want to understand why it is bad.

so in my core.js file I have functions like this:

var getMyLocation = function(location) {
var promiseResolver = Promise.defer();

$.get('some/rest/api/' + location)
.then(function(reponse) {
.catch(function(error) {

return promiseResolver.promise;

And then in my getLocation.js file I have the following:

var core = require('core');
var location = core.getMyLocation('Petersburg')
.then(function(response) {
// do something with data
}).catch(throw error);

After reading the Bluebird docs and many blog posts about the deferred anti-pattern I wonder if this pattern is practical. I could change this to the following:


var getMyLocation = function(location) {
var jqXHR = $.get('some/rest/api/' + location);
return Promise.resolve(jqXHR)
.catch(TimeoutError, CancellationError, function(e) {
// Don't swallow it
throw e;


var location = core.getMyLocation('Petersburg')
.then(function(response) {
// do something
.catch(function(error) {
throw new Error();

I guess I'm confused by what is the best way to have a central library that handles xhr requests using jquery for the calls, but Bluebird for the promises.


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.

    return $.get(...);
    // 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.