[英]Pass variable to callback - nodejs
I'm creating a simple Messenger bot, using unofficial Facebook Chat API ( https://github.com/Schmavery/facebook-chat-api ) and Node.js. 我使用非官方的Facebook Chat API( https://github.com/Schmavery/facebook-chat-api )和Node.js创建了一个简单的Messenger机器人。
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? 而且,我的问题是:如何将警报数组传递给此回调,以便能够将消息发送给特定用户?
Looks like that you change i
variable somewhere, and because of that when callback is called alarms[i]
is undefined. 看起来您在某处更改了i
变量,因此在调用回调时, alarms[i]
未定义。 You need to store alarms[i]
in a new variable and use it in callback: 您需要将alarms[i]
存储在新变量中,并在回调中使用它:
let alarm = alarms[i];
api.getUserID(alarm.user, (err, users) => {
if(err) {
return console.error(err);
}
api.sendMessage(alarm.message, users[0].userID);
});
Appear that you are using for loop outside. 似乎您正在使用for循环外部。 Try pass your var that way: 尝试以这种方式传递您的var:
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: 只需输入逗号和其他var,例如:
(function (alarm, user){
// your code here
})(alarm, user);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.