簡體   English   中英

出現錯誤(ReferenceError: steamMSG is not defined),即使我給它賦值

[英]Getting an error (ReferenceError: steamMSG is not defined) even though I assign it a value

我收到此錯誤消息“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

那是因為行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
        });
});

理想的解決方案是使用承諾。

您需要將 bot.sendMessage 調用放在請求的回調中。

由於“請求”需要時間來發出請求,因此它有一個完成時的回調。 這意味着 bot.sendMessage 實際上在請求完成之前被調用,因此 steamMSG 尚未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM