[英]Sharing variables across event callbacks in NodeJS
I'm trying to build a FB messenger bot using messenger-bot module. 我正在尝试使用messenger-bot模块构建FB Messenger机器人。 Here's my sample code
这是我的示例代码
bot.on('message', (payload, reply) => {
let userData = payload.message.text;
bot.getProfile(payload.sender.id, (err, profile) => {
if (err) {
console.log(err);
// throw err
}
else {
text = {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Pick an option?",
"buttons":[
{
"type":"postback",
"title":"Option 1",
"payload":"first_option"
},
{
"type":"postback",
"title":"Option 2",
"payload":"second_option"
}
]
}
}
};
postBack(text, payload.sender.id, profile);
}
});
});
bot.on('postback', (payload, reply) => {
let text = payload.postback.payload;
bot.getProfile(payload.sender.id, (err, profile) => {
//Do something with the userData and the selected option
});
})
Now how do I access userData
in the event callback for "postback"
? 现在如何在事件回调中为
"postback"
访问userData
? I could think of only the following solution 我只能想到以下解决方案
Pass the userData
as part of the payload of the options, something like 将
userData
作为选项有效负载的一部分传递,例如
"buttons":[
{
"type":"postback",
"title":"Option 1",
"payload":"first_option||"+userData
}
and parse it again in the "postback"
callback. 并在
"postback"
回调中再次对其进行解析。
Is there a better way to do this? 有一个更好的方法吗? In other words how to share variables across callbacks in NodeJS/ JavaScript?
换句话说,如何在NodeJS / JavaScript中的回调之间共享变量?
假设这需要服务多个用户,因此无法将userData的范围扩大,那么您要么将其持久化在数据库/缓存中,然后从“回发”中进行查询,要么使用将其作为有效内容的一部分的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.