简体   繁体   English

如何在函数外使用变量?

[英]How to use a variable outside of function?

Hey guys I'm having trouble using the "appIds" variable outside the function scope, how can this be done? 大家好,我在功能范围之外使用“ appIds”变量时遇到问题,该怎么办? Here's the script below used in NodeJS: 这是NodeJS中使用的以下脚本:

var appIds = [];

request("http://api.steampowered.com/ISteamApps/GetAppList/v2?format=json", function(error, response, body) {
    if (!error && response.statusCode == 200) {

        var o = JSON.parse(body);
        appIds = o.applist.apps.map(v => v.appid);
        // console.log(appIds); works within scope.
    }
});

console.log(appIds);

That is wont work since it is an asynchronous call. 那是无效的,因为它是一个异步调用。 You can do only inside the callback. 您只能在回调内部执行。

What you are doing in the commented code is the right way to handle it. 您在注释的代码中所做的就是正确的处理方式。

request("http://api.steampowered.com/ISteamApps/GetAppList/v2?format=json", function(error, response, body) {
 if (!error && response.statusCode == 200) {

    var o = JSON.parse(body);
    appIds = o.applist.apps.map(v => v.appid);
    console.log(appIds); //works within scope.
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM