How to return from a promise if Ajax is not required?

381 views Asked by At

I am using jQuery promises to pre-fill the value of a select option. This works fine, but my question is about what to do when an Ajax call is not actually required, so the code does not return a promise.

The code below works fine if this.orgId is not undefined. But when it is not, I get an error:

getFormValues: function() {
    var _this = this;
    return _this.prefillOrgs()
                .then(function(orgId) {
                  _this.globalOptions.orgId = orgId;
                  return true;
                });
},

prefillOrgs: function() {
    if (typeof this.orgId !== 'undefined') {
        return $.ajax({
            type: 'GET',
            url:  '/api/1.0/org_code?exact=true&q=' + this.orgId,
            dataType: 'json',
            context: this
        });
    } else {
        // Doing this produces an error
        return [];
    }
}

The error returned:

Uncaught TypeError: _this.prefillOrgs(...).then is not a function

I guess this is because returning [] is not a promise and does not have a .then() method defined. However, I would like to return [] as my data payload in this case.

How can I get around this? I'd prefer not to make an unnecessary Ajax call if possible.

UPDATE: The other thing worth noting is that I need the this context inside whatever is returned.

2

There are 2 answers

2
Benjamin Gruenbaum On BEST ANSWER

Use $.when

 return $.when([]);

It converts a value (or group of values, or a promise) to a promise.

In ES6 the responsibilities are seprate - converting a value or promise to a promise is done with Promise.resolve

0
Eugene On

If a function is sometimes asynchronous and can return promise than it makes sense to always return promise for consistency. jQuery has $.when() that can create promises from values. So

return [];

will become

return $.when([]);