0

First of all, sorry for the vague title. I didn't know how to summarize my problem in the title.

I'm currently learning NodeJS & Express and decided to build a TwitchTV chat bot as a little exercise. For this I'm using tmijs.

Here is the problem I'm currently facing:

function getActivatedChannels() {
  var channels = [];
  User.find(function(err, users) {
    if (err) console.error(err);
    for (var i = 0; i < users.length; i++) {
      if (users[i].activated) {
        channels.push(users[i].name);
      }
    }
    console.log(channels);
  });
  return channels;
}

//tmi.js options
var options = {
  options: {
    debug: true
  },
  connection: {
    cluster: 'aws',
    reconnect: true
  },
  identity: {
    username: credentials.tmijs.username,
    password: credentials.tmijs.password
  },
  channels: getActivatedChannels()
};

var client = new tmi.client(options);
client.connect();

The problem here is that getActivatedChannels() seems to take too long. client.connect() is called before the first function resolves, leading to the client not connecting to any channels. A way to fix this is wrapping everything after var options in a setTimeout(), but that hardly seems like a good way to solve this.

What better way is there to fix this problem?

eRodY
  • 635
  • 1
  • 6
  • 10
  • 1
    You're trying to return content from a asynchronous method. A timeout isn't the answer, learning to work with asynchronous code is. – adeneo Jul 17 '16 at 13:53
  • You should look into callback or promises. – Rajesh Jul 17 '16 at 13:54
  • *"The problem here is that `getActivatedChannels()` seems to take too long."* No, the problem is it's **asynchronous**. It could complete in a nanosecond, but your code would still see no channels. See the linked question for how to solve it (using a callback, directly or via promises). – T.J. Crowder Jul 17 '16 at 13:55
  • If you wish to connect and then update channel list, set `[]` as channels and then call function to get active channels and in its success, you can try `client.channels = something`. Not sure though – Rajesh Jul 17 '16 at 13:57

0 Answers0