【问题标题】:(Javascript) Global Variable inside function is not changing value before https request(Javascript) 函数内部的全局变量在 https 请求之前没有改变值
【发布时间】:2020-09-05 06:24:46
【问题描述】:

我初始化硬币,然后在 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();
    }

服务器连接正常,因为如果msg.content === 'money',它会正确回复nice。如果msg.content === 'BTC/USD',则不回复。

在生成https.request 之前,它似乎没有改变coin 的值。

感谢您的帮助,谢谢。

【问题讨论】:

  • path 上的 path 值不会因 coin 变量的更改而实时更新。一旦计算出字符串,它们就不再以任何方式联系在一起。
  • 您必须先options.path = 'your lead in string' + coin; 才能提出更新请求。
  • response.on('data') 也不会返回完整的数据,它会返回您必须累积然后连接到response.on('end') 的数据块。请参阅:stackoverflow.com/q/15714499/9867451 了解更多信息
  • options.path = 'your lead in string' + coin; 工作,你能把这个回答给我可以批准吗
  • @ibrahimmahrir ,这就是我需要进行所有解析和字符串化的原因吗?

标签: javascript https discord.js


【解决方案1】:

我确实认为你的代码是异步的,所以你应该等到请求/响应完成。

如果您想一次性发送所有令牌

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);

    }})

否则每次调用数据函数处理程序时都会发送一条消息:

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()
                })
            });
        })

    }})
    ````

【讨论】:

猜你喜欢
  • 2020-04-04
  • 1970-01-01
  • 2019-09-15
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
相关资源
最近更新 更多