2015-04-23 69 views
1

我正在嘗試在JQuery每個循環內對API進行外部AJAX調用。JavaScript範圍/提升OR承諾/延期?

這是我到目前爲止的代碼。

getStylesInfo(tmpMake, tmpModel, tmpModelYear, tmpSubmodel).done(function(data){ 
    var holder = []; 

    $.each(styles, function(index, value) { 
     var tempValue = value; 
     var temp = getNavigationInfo(value.id); 

     $.when(temp).done(function(){ 
      if(arguments[0].equipmentCount == 1){ 
       holder.push(tempValue); 
       console.log(holder); 
      } 
     }); 
    }); 
}); 

console.log(holder); 

function getStylesInfo(make, model, year, submodel){ 
    return $.ajax({ 
    type: "GET", 
    url: apiUrlBase + make + '/' + model + '/' + year + '/' + 'styles? fmt=json&' + 'submodel=' + submodel + '&api_key=' + edmundsApiKey + '&view=full', 
    dataType: "jsonp" 
}); 


function getNavigationInfo(styleId){ 
    return $.ajax({ 
    type: "GET", 
    url: apiUrlBase + 'styles/' + styleId + '/equipment?availability=standard&name=NAVIGATION_SYSTEM&fmt=json&api_key=' + edmundsApiKey, 
    dataType: "jsonp" 
}); 

getStylesInfo()返回類似於此的內容。有關汽車模型信息的對象數組。

var sampleReturnedData = [{'drivenWheels': 'front wheel drive', 'id': 234321}, {'drivenWheels': 'front wheel drive', 'id': 994301}, {'drivenWheels': 'rear wheel drive', 'id': 032021}, {'drivenWheels': 'all wheel drive', 'id': 184555}]; 

我通過sampleReturnedData試圖循環並使用每個ID爲與getNavigationInfo()函數不同的AJAX調用的參數。

我想循環查看結果並進行檢查。如果它是真的,那麼我想把整個對象推到holder數組中。

問題是console.log(holder)函數外部返回一個空數組。 if語句中的console.log(持有者)正常工作。

我不確定這是範圍/提升問題還是我使用延遲方法的問題?

我已閱讀this問題,很多人喜歡它。他們建議使用

async:false 

或者更好地重寫代碼。我曾嘗試過無數次使用控制檯調試器。我不想將它設置爲false。我只是不確定到底發生了什麼。

我也讀過關於通過this提升的文章。

我相信它與延遲有關,但我沒有足夠的JS知識來解決它。

謝謝!

回答

3

我不確定這是範圍/提升問題還是我使用延遲方法的問題?

事實上,它既是:

所以,你應該做的確實是重寫代碼正確使用承諾:-)

getStylesInfo(tmpMake, tmpModel, tmpModelYear, tmpSubmodel).then(function(data) { 
    var holder = []; 
    var promises = $.map(data.styles, function(value, index) { 
     return getNavigationInfo(value.id).then(function(v){ 
      if (v.equipmentCount == 1) 
       holder.push(value); 
     }); 
    }); 
    return $.when.apply($, promises).then(function() { 
     return holder; 
    }); // a promise for the `holder` array when all navigation requests are done 
}).then(function(holder) { 
    console.log(holder); // use the array here, in an async callback 
}); 
+1

另外,我猜'styles'應該是一個嵌套的對象在'data'內 – wahwahwah