我用以下代码创建了模块我的模块:
var request = require('request');
var EventEmitter = require('events').EventEmitter;
var User = new EventEmitter();
var userFbInfos = new EventEmitter();
//database and calls the get started conversation.
User['checkUserRegistered'] = function (userID) {
//if registered and have phone number then nothing to do otherwise, get user infos return it and last ask his phonenumber
//Now we consider that the user is not registered. So we get is infos
userFbInfos.getInfos(userID);
userFbInfos.on('gotten', function (err, userInfos) {
User.emit('checked',err, userInfos);
});
}
//This gets user info from Facebook and notifies when the information is gotten via event gotten
//The thing is as node is event driven if you request the user info and run a code before getting that info, the userinfos will be null.
userFbInfos['getInfos'] = function (userID) {
request.get("https://graph.facebook.com/v2.6/" + userID + "?fields=first_name,last_name,locale,gender,timezone,profile_pic&access_token=" + process.env.page_token,
function (err, response, body) {
userFbInfos.emit('gotten',err,JSON.parse(body));
});
}
exports.userFbInfos = userFbInfos;
exports.User = User;
然后在我的app.js中,我按如下方式使用它:
modulemy = require('./modulemy.js');
var user = modulemy.User;
//Checking if user is registered.
user.checkUserRegistered('123');
//This variable checks if the event was trigger before already to not execute the code twice.
var called = false;
user.on('checked', function (err, userInfos) {
if (!called){
console.log("Call Checked");
var name = "";
if (typeof (userInfos) != 'undefined') {
name = userInfos['first_name'];
}
console.log("Yes you are there");
called = true;
}
});
问题是检查事件被多次触发...我不知道问题出在哪里...我需要帮助。
最佳答案
从fb接收软件包时可能会出现问题。如果来自查询的输入数据与之前查询的数据相同,则尝试增加一些变量。
关于javascript - Nodejs事件被多次发出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48316609/