Javascript scope/hoisting 或 promises/deferreds?

Javascript scope/hoisting OR promises/deferreds?

我正在尝试在每个循环 Jquery 中对 API 进行外部 AJAX 调用。

这是我目前的代码。

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() returns 与此类似。包含汽车模型信息的对象数组。

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 并在使用 getNavigationInfo() 函数的不同 AJAX 调用中将每个 ID 用作参数。

我想遍历结果并进行检查。如果是,那么我想将整个对象推送到 holder 数组。

问题是 console.log(holder) 在函数 returns 之外是一个空数组。 if 语句中的 console.log(holder) 工作正常。

我不确定这是 scope/hoisting 问题还是我使用 deferreds 的方式有问题?

我已阅读 this 个问题,很多人都喜欢它。他们建议使用

async:false

或者重写代码更好。我已经多次尝试并使用控制台调试器。我不想将其设置为假。我只是不确定到底发生了什么。

我还通过 this 文章阅读了关于提升的内容。

我相信它与 deferreds 有关,但我没有足够的 JS 知识来弄清楚它。

谢谢!

I am not sure if this is a scope/hoisting issue or a problem with the way I am using deferreds?

其实两者都是:

  • holder 仅在回调函数内声明(作为局部变量),因此 undefined 在函数外。
  • 并且 console.log 在异步回调函数确实用值填充数组之前执行,因此即使 holder 在范围内它仍然是空的。另见 Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

所以您确实应该重写您的代码以正确使用 promises :-)

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
});