0

I'm creating a simple Messenger bot, using unofficial Facebook Chat API (https://github.com/Schmavery/facebook-chat-api) and Node.js.

For now, I'm working on sending messages to specific users, on a specific time. Here's part of my code:

if(msgdate.getTime() <= currdate.getTime()){

    console.log(alarms[i].message);
    // output: test

    api.getUserID(alarms[i].user, (err, users) => {
        if(err) return console.error(err);

        api.sendMessage(alarms[i].message, users[0].userID);
        // TypeError: Cannot read property 'message' of undefined
    });
}

And, my question is: how could I pass alarms array to this callback, so I'd be able to send message to a specific user?

1
  • Try to use async/await. See if that helps. Commented Oct 3, 2017 at 14:43

2 Answers 2

1

Looks like that you change i variable somewhere, and because of that when callback is called alarms[i] is undefined. You need to store alarms[i] in a new variable and use it in callback:

let alarm = alarms[i];
api.getUserID(alarm.user, (err, users) => {
  if(err) {
    return console.error(err);
  }
  api.sendMessage(alarm.message, users[0].userID);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Appear that you are using for loop outside. Try pass your var that way:

var alarm = alarm[i];
(function (alarm) {
    if(msgdate.getTime() <= currdate.getTime()){

    console.log(alarm.message);
    // output: test

    api.getUserID(alarm.user, (err, users) => {
        if(err) return console.error(err);

        api.sendMessage(alarm.message, users[0].userID);
        // TypeError: Cannot read property 'message' of undefined
    });
})(alarm);

Maybe you need to pass other vars too. Just put a comma and other var, example:

(function (alarm, user){
    // your code here
})(alarm, user);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.