2015-06-09 58 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([]);