Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/436.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果不需要Ajax,如何从承诺中返回?_Javascript_Jquery_Ajax_Promise - Fatal编程技术网

Javascript 如果不需要Ajax,如何从承诺中返回?

Javascript 如果不需要Ajax,如何从承诺中返回?,javascript,jquery,ajax,promise,Javascript,Jquery,Ajax,Promise,我使用jQuery承诺预先填充select选项的值。这很好,但我的问题是,当实际上不需要Ajax调用时,该怎么做,因此代码不会返回承诺 如果this.orgId未定义,则下面的代码可以正常工作。但如果不是,我会得到一个错误: getFormValues: function() { var _this = this; return _this.prefillOrgs() .then(function(orgId) {

我使用jQuery承诺预先填充
select
选项的值。这很好,但我的问题是,当实际上不需要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
上下文

 return $.when([]);
它将一个值(或一组值,或一个承诺)转换为一个承诺


在ES6中,职责是分离的-将值或承诺转换为承诺是通过
承诺来完成的。如果函数有时是异步的,并且可以返回承诺,则解决

问题,因为始终返回承诺以保持一致性是有意义的。jQuery有一个可以从值创建承诺的函数。所以

return [];
将成为

return $.when([]);

看一看令人敬畏的感谢,它返回的
[]
很好,但我已经失去了
这个
上下文-是否还需要包含上下文?检查文档,但看不到如何…没有直接的方法,而且在jQuery3.0中,上下文参数中断。我强烈建议将上下文作为响应的一部分传递,或者在接收端传递.bind