2015-06-09 60 views
4

我正在使用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上下文。

+0

看看[递延](https://api.jquery.com/deferred.promise/) – Nicolai

回答

3

使用$.when

return $.when([]); 

它可以转换的值(或值的组,或一个承诺)到的承诺。

在ES6的职责是seprate - 转换价值或承诺,承诺与Promise.resolve

+0

真棒感谢,返回'[]'很好,但我已经失去了我的'这个'上下文 - 是否有包含上下文?检查文档,但看不到... – Richard

+1

没有直接的方法,而且在jQuery 3.0中,上下文参数被打破。我强烈建议将上下文作为响应的一部分传递给接收方或将其绑定到接收方 –

+0

好吧,将它传回给用户很好,谢谢! – Richard

1

做如果一个函数有时异步的,比它是有道理的始终一致性返回承诺可以退货的承诺。 jQuery有$.when()可以创建值的承诺。所以

return []; 

将成为

return $.when([]);