无法在请求中编辑变量

时间:2018-08-24 22:28:55

标签: javascript json node.js request

在请求中时,我正在尝试修改变量。但是我不知道为什么它没有被修改。

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

1 个答案:

答案 0 :(得分:2)

您的代码可以正常工作,并且您的sgameh变量已根据需要进行了修改。 request函数是异步的

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

先执行

console.log(sgameh) // THIS WORKS, BUT IT ISN'T WHAT I WANT