2015-04-23 73 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