我收到此错误," ReferenceError:未定义steamMSG,"即使我正在为steamMSG分配一个值。我真的很困惑,因为当我在控制台中记录它时它会工作并显示它有一个值。
代码:
if (command === "hex.steam") {
var url = 'https://api.steampowered.com/ISteamUser/ResolveVanityURL/v1/?key='+steamKey+'&format=json&vanityurl='+arguements;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
} else {
console.log("Got an error: ", error, ", status code: ", data.statusCode);
}
var steamMSG = data.response.steamid;
console.log(steamMSG);
});
bot.sendMessage({
to: channelID,
message: steamMSG
});
}
错误在这一行:
message: steamMSG
答案 0 :(得分:0)
那是因为行var steamMSG = data.response.steamid;
在异步函数中,bot.sendMessage()
在定义之前被调用。
最简单的解决方案是将bot.sendMessage()
粘贴到函数中:
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
} else {
console.log("Got an error: ", error, ", status code: ", data.statusCode);
}
var steamMSG = data.response.steamid;
console.log(steamMSG);
bot.sendMessage({
to: channelID,
message: steamMSG
});
});
理想的解决方案是使用承诺。
答案 1 :(得分:0)
您需要将bot.sendMessage调用放入请求的回调中。
因为"请求"需要时间来提出请求,它会在完成时回调。这意味着在请求完成之前实际调用了bot.sendMessage,因此尚未定义steamMSG。