我正在使用 jQuery promise 预填充 select
选项的值。这工作正常,但我的问题是当实际上不需要 Ajax 调用时该怎么做,因此代码不返回 promise 。
如果 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
我猜这是因为返回 []
不是一个 promise ,并且没有定义 .then()
方法。但是,在这种情况下,我想返回 []
作为我的数据负载。
我该如何解决这个问题?如果可能,我不想进行不必要的 Ajax 调用。
更新:另一件值得注意的事情是,无论返回什么,我都需要 this
上下文。
最佳答案
使用$.when
return $.when([]);
它将一个值(或一组值,或一个 promise )转换为一个 promise 。
在 ES6 中,职责是分开的 - 将值或 promise 转换为 promise 是使用 Promise.resolve
关于javascript - 如果不需要 Ajax,如何从 promise 中返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30731015/