我正在使用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