0

I'm trying to modify a variable when I'm inside a request. But I don't know why it doesn't get modified.

const request = require("request");
var all = JSON.parse(body);
var steamplayer = all['response']['players']['player'][0];
var sgameh = "Nessun gioco";
request({
    url: "https://example.com",
    method : 'GET'
}, function (error, response, body){
    var sgameall = JSON.parse(body);
    var fgame = sgameall['response']['games'].filter(function(item) {
        return item.appid == steamplayer.gameid;
    });
    sgameh = parseFloat(fgame[0].playtime_forever / 60).toFixed(2);
    console.log(sgameh) // THIS WORKS, BUT IT ISN'T WHAT I WANT
})
console.log(sgameh) // SHOULD RETURN A NUMBER, BUT RETURN Nessun gioco
Alwe
  • 27
  • 1
  • 8

1 Answers1

2

Your code works correctly and your sgameh variable is modified as you want it to be. The request function is asynchroneous so

console.log(sgameh) // SHOULD RETURN A NUMBER, BUT RETURN Nessun gioco

is executed before

console.log(sgameh) // THIS WORKS, BUT IT ISN'T WHAT I WANT
Baboo
  • 4,008
  • 3
  • 18
  • 33
  • So what should i do to adjust this? – Alwe Aug 24 '18 at 22:38
  • Here is a good [link](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) @Hamms suggested – Baboo Aug 24 '18 at 22:41