访问一个变量,它是由一个异步函数输出 [英] Access to a variable, which is output from an async function

查看:329
本文介绍了访问一个变量,它是由一个异步函数输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个片段中的一个问题:

I have a problem with this snippet:

d3.csv("data/airports.csv", function(err, a) {
    var count=0;

    a.forEach(function(i){
       if(i.iata_faa == ""){}
       else {
             count++;
             addpoint(i.lon, i.lat,i);
      }
    });

    airports=a;
    myDataIsReady();
    console.log(count);
});

function myDataIsReady(){
    console.log(airports);
    return airports;
}

console.log(airports);

注意机场是一个全局变量在这里。

Notice that airports is a global variable here.

我需要处理的变量机场其他功能,但值为空,我想是因为CSV文件尚未处理完毕即空,右?

I need to handle the variable airports for another function, but the value is null, I think that is null because the csv file has not yet been processed completely, right?

我该如何解决这个问题?

How I resolve it?

推荐答案

通常对于异步功能,你推一个回调(函数引用)到异步方法,因此,它的Ajax调用完成时处理数据。你不会从这种类型的函数返回的数据,数据注入到它。

Generally for async functions, you push a callback (a function reference) into the async method, so that it processes the data when the ajax call completes. You don't return data from that type function, you inject data into it.

这篇关于访问一个变量,它是由一个异步函数输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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