Nodejs事件被多次发出

时间:2018-01-18 08:16:29

标签: javascript node.js

我使用以下代码创建了我的模块 modulemy

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;
                            }
                        });

问题是被检查的事件被多次触发......我不明白问题出在哪里......我需要帮助。

1 个答案:

答案 0 :(得分:2)

从fb接收包时可能会出现问题。如果来自查询的输入数据与之前的查询中的输入数据相同,请尝试计算一些变量。