我正在使用jQuery承诺预填充select
选项的值。这工作正常,但我的问题是如果实际上并不需要Ajax调用该怎么做,所以代码不会返回承诺。如果不需要Ajax,如何从承诺中退出?
如果this.orgId
未定义,以下代码正常工作。但是,当它不是,我得到一个错误:
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 [];
}
}
返回的错误:
Uncaught TypeError: _this.prefillOrgs(...).then is not a function
我想这是因为返回[]
不是一个承诺,并没有定义一个.then()
方法。但是,在这种情况下,我想返回[]
作为我的数据负载。
我该如何解决这个问题?如果可能,我宁愿不要进行不必要的Ajax调用。
更新:另一件值得注意的是,无论返回什么,我都需要this
上下文。
看看[递延](https://api.jquery.com/deferred.promise/) – Nicolai