在fetch之外定义的对象但不在

时间:2016-11-23 22:12:09

标签: javascript node.js twitch

我正在使用tmi.js在www.twitch.tv上获取聊天消息的数据。

这是我的代码:

const tmi = require('tmi.js');
require('dotenv').config();

const options = {
  options: {
    debug: true
  },
  identity: {
    username: process.env.OAUTH_USERNAME,
    password: process.env.OAUTH_PASSWORD
  },
  connection: {
    reconnect: true
  },
  channels: [`instak`]
};

const client = new tmi.client(options);

client.on(`chat`, (channel, userstate, message/*, self */) => {
  console.log(userstate.username); //This logs my userstate, I can see the username which is passed on correctly.
  switch (message) {
    case `!kluiten`:
      fetch(`http://localhost:8000/api/users/${userstate.username}`) // fetch from Express.js server
      .then(response => response.json())
      .then(result => {
        console.log(`USERSTATE IS`, userstate);
        client.action(channel, `${userstate[`display-name`]}, you've got ${result.instakluiten} instakluiten.`);
      });
      break;
    default:
      break;
  }
});

// Connect the client to the server..
client.connect();

正如我在console.log(userstate)之后的注释部分中所说,我得到了我期望的所有正确信息,因此在switch case和fetch之外。但是,当我在fetch中记录userstate.username时,userstate是未定义的......我不明白为什么会发生这种情况,因为当我在前端做到这一点时我没有遇到任何问题......现在我正在做它在节点中并且未定义......

这看起来像是一个常见的“你需要等待你的回复” - 问题,但我没有看到这个问题的逻辑解释,因为在client.on(chat)中定义了userstate ......我很困扰。

0 个答案:

没有答案
相关问题