0

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);
Kai
  • 89
  • 1
  • 6

1 Answers1

3

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.
  }
});
shershen
  • 9,875
  • 11
  • 39
  • 60
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I see are there no other way around using it outside the scope? Because the code continues along with a second request which needs to use the results of the first request. – Kai May 14 '16 at 20:52
  • You have to wrap them one in another. You cannot just go ahead and assuming it. you have fire another request in first request callback. – Suresh Atta May 14 '16 at 20:57
  • You can make the request synchronous and you can then have your bad way of coding work without extra effort. – N.B. May 14 '16 at 21:15