(仍然)对javascript闭包,ajax和返回值更加困惑 [英] (still) more confusion over javascript closures, ajax, and return values

查看:115
本文介绍了(仍然)对javascript闭包,ajax和返回值更加困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery .get()方法和javascript for循环来处理来自外部文件的某些数据.我已经阅读了几个小时的关于stackoverflow的闭包和从回调返回值的信息,但我仍然感到困惑,为什么它不起作用.

I'm trying to use JQuery .get() method and a javascript for loop to process some data from an external file. I've read about closures and return values from callbacks on stackoverflow for a couple hours, and i'm still confused why this isn't working.

相对于内部回调函数,变量 headers countryData 是否在范围上不是全局的?它们已在回调函数中按预期分配值,但是一旦完成,如何访问它们呢?还有可能是使用alert()函数的例子吗?

Are the variables headers and countryData not global in scope with respect to the inner callback function? They are being assigned values as intended within the callback function, but then how do i access them once that is complete? And possibly an example wihtout using the alert() function?

function processData(inCSV){
    var headers;  
    var countryData = [];
    $.get(inCSV, function(data) {
        var lines = data.split('\r\n');
        for(var i=0;i<=lines.length-1;i++){
            var lineData = lines[i].split(',');
            if(i != 0){
                countryData[lineData[1]] = lineData.slice(2,lineData.length);
            } else {
                headers = lineData.slice(2,lineData.length);
            }
        }
        console.log('inside',headers);  // output 'inside ["1971", "1972", "1973" ...'
        console.log('inside',countryData['Brazil']);  // output 'inside ["56.4", "54.6", ..'
    });
    console.log('outside',headers);  // output 'outside undefined' ...!?
    console.log('inside',countryData['Brazil']);    // output 'outside undefined' ...!?
}   

推荐答案

问题不是闭包,问题是异步函数. $ .get()连接到服务器,并在服务器返回答案时运行其回调函数.但是$ .get()是在发送请求后完成的,而不是在返回响应时完成的.因此,在执行回调函数之前,最后两行console.log()行正在运行.

The problem isn't the closure, the problem is asynchronous functions. $.get() connects to a server, and runs its callback function when the server returns an answer. But $.get() completes once the request is sent, not when the response is returned. So your last two console.log() lines are running before the callback function is executed.

一旦执行了回调函数,您就只能访问headerscountryData变量,并且您知道发生的唯一地方是在回调函数本身内部.或它调用的其他代码.

You can only access the headers and countryData variables once the callback function has executed, and the only place you know that has happened is inside the callback function itself. or other code that it calls.

这篇关于(仍然)对javascript闭包,ajax和返回值更加困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆