简体   繁体   English

(Javascript)函数内部的全局变量在https请求之前没有改变值

[英](Javascript) Global Variable inside function is not changing value before https request

I initialize coin and then give it a value inside the if-statement:我初始化 coin,然后在 if 语句中给它一个值:

const https = require('https');
var coin = ''
var options = {
  "method": "GET",
  "hostname": "rest.coinapi.io",
  "path": "/v1/exchangerate/" + coin,
  "headers": {'X-CoinAPI-Key': 'secretkey'}
};

client.on('message', msg => {
    if (msg.content === 'money') {
        msg.reply('nice');
    }
    if (msg.content === 'BTC/USD') {
        coin = msg.content;
        var request = https.request(options, function (response) {
            response.on('data', d => {
                var json = JSON.parse(d.toString())
                var value = JSON.stringify((json.rate).toPrecision(7))
                value = value.replace(/\"/g, "")
                msg.reply(coin + ": $" + value);
            });
        });
        request.end();
    }

The server connection is working because if msg.content === 'money' , it properly replies with nice .服务器连接正在工作,因为如果msg.content === 'money' ,它会正确回复nice If msg.content === 'BTC/USD' , it does not reply.如果msg.content === 'BTC/USD' ,它不会回复。

It seems to not be changing the value of coin before it makes the https.request .在发出https.request之前,它似乎没有改变coin的价值。

Any help is appreciated, thank you.任何帮助表示赞赏,谢谢。

I do think that your code is async so you should wait till the request/response has finished.我确实认为您的代码是异步的,因此您应该等到请求/响应完成。

If you want to send all the tokens once如果您想一次发送所有令牌

const https = require('https');
let coin = ''
let options = {
  "method": "GET",
  "hostname": "rest.coinapi.io",
  "path": "/v1/exchangerate/" + coin,
  "headers": {'X-CoinAPI-Key': 'secretkey'}
};

client.on('message', async (msg) => {
    if (msg.content === 'money') {
        msg.reply('nice');
    }
    if (msg.content === 'BTC/USD') {
        coin = msg.content;
        const res = await new Promise((res, rej)=>{
            https.request(options, function (response) {
                const tokens = []
                response.on('data', d => {
                    var json = JSON.parse(d.toString())
                    var value = JSON.stringify((json.rate).toPrecision(7))
                    value = value.replace(/\"/g, "")
                    tokens.push(coin + ": $" + value)
                });
                response.on("error", (err)=>{
                    console.error(err);
                    rej(null)
                })

                response.on("end", () => {
                    res(tokens.join("\n"))
                })
            });
        })

        msg.reply(res === null ? "error" : res);

    }})

otherwise send a message everytime the data function handler is called :否则每次调用数据函数处理程序时发送一条消息:

const https = require('https');
let coin = ''
let options = {
  "method": "GET",
  "hostname": "rest.coinapi.io",
  "path": "/v1/exchangerate/" + coin,
  "headers": {'X-CoinAPI-Key': 'secretkey'}
};

client.on('message', async (msg) => {
    if (msg.content === 'money') {
        msg.reply('nice');
    }
    if (msg.content === 'BTC/USD') {
        coin = msg.content;
        await new Promise((res, rej)=>{
            https.request(options, function (response) {
                response.on('data', d => {
                    var json = JSON.parse(d.toString())
                    var value = JSON.stringify((json.rate).toPrecision(7))
                    value = value.replace(/\"/g, "")
        msg.reply(coin + ": $" + value);
                });
                response.on("error", (err)=>{
                    console.log(err);
                    rej()
                })

                response.on("end", ()=>{
                    res()
                })
            });
        })

    }})
    ````

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM