简体   繁体   中英

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? Here's the script below used in 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.
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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