AJAX call inside Ember.RSVP.Promise

231 Views Asked by At

I have the following common code to invoke AJAX requests. My question is if the "return" keyword is necessary for the $.ajax (since doing $.ajax would anyways return a promise) OR if it is for some other purpose ?

doXhr: function(postData, requestUrl){  
    var promise = new Ember.RSVP.Promise(function(resolve, reject) {        
        return $.ajax({ //Is the "return" required on this line ?
            url: requestUrl,

        })
        .done(function(response, status, xhrObject) {         
          resolve(response);
        })
        .fail(function(xhrObject, status, error){           
            reject(errorObj);
        });
    })  
    return promise;
},
1

There are 1 best solutions below

5
NullVoxPopuli On

just like other promise libraries (Native, Bluebird, etc), the resolve, reject functions are actually callbacks, so there is no need for a return inside the new Promise. (If you never call resolve or reject though, your promise will be pending forever).

The only return that is needed in the return of the RSVP.Promise like what you have at the bottom -- though only if you are awaiting or thening doXhr

Also, neat side-tip:

With the the more recent ember, you can just do:

import { Promise } from 'rsvp';

new Promise((resolve, reject) => {
  // stuff
});

Edit

for how the function body of the promise get's executed, you'll need to look at the constructor of the Promise: https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js#L143

the resolver function (the function you define when making a new promise) is passed to here https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/-internal.js#L231 and then evaluated.

Hope this helps!