Javascript 范围/提升或 promise /延迟?

标签 javascript jquery ajax jquery-deferred hoisting

我正在尝试在 Jquery each 循环中对 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() 返回与此类似的内容。包含汽车模型信息的对象数组。

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(holder) 正常工作。

我不确定这是范围/提升问题还是我使用 deferred 的方式有问题?

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

async:false

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

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

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

谢谢!

最佳答案

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

其实两者都是:

所以您确实应该重写您的代码以正确使用 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
});

关于Javascript 范围/提升或 promise /延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834259/

相关文章:

javascript - 使用 MathJax 和 JQuery 插入 MathML

jQuery:keydown 事件多次触发

javascript - 我的表单未将参数存储在模型中

javascript - 使用 AJAX 添加 select onchange

jquery - Wordpress AJAX 不返回自定义作者元

javascript - 将数组大小设置为等于文件夹中的文件数

javascript - React JS获取数组中数字的总和

javascript - 检测退出全屏 html 视频

jquery append() 不写结束标记

php - JSON 不将数组数据传递给 PHP