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.
Use
$.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