Nodejs事件被多次发射

export function postComment(req, res) { const user = decodeToken(req); let saveComment, saveJob, saveUser, activity, jobUser; function pushToJob(comment) { saveComment = comment; Job.findById(req.params.id) .then((data) => { job = data; data.comments.push(saveComment._id) return data.save() }).catch((err) => { throw new Error(`The error at pushing to job is ${err}`) }) } function updateCommentWithJobId(job) { saveComment.jobId = { _id: job._id, title: job.title } return saveComment.save() } function addActivityToUser(comment) { saveComment = comment; User.findById(user._id) .then((data) => { saveUser = data; activity = { activity: 'comment', comment: saveComment._id, jobAuthor: { _id: saveJob.userId._id, name: saveJob.userId.name } } saveUser.activities.unshift(activity); return saveUser.save() }).catch((err) => { throw new Error(`The error at addActivityToUser is ${err}`) }) } function addUserToComment(user) { saveUser = user; saveComment.userId = { _id: saveUser._id, name: saveUser.name, profile_image: saveUser.profile_image } return saveComment.save() } function addActivityToJobUser(comment) { saveComment = comment User.findById(saveJob.userId) .then((data) => { if (saveJob.userId !== user._id) { data.activities.unshift(activity); } return data.save() }).catch((err) => { throw new Error(`The error at addActivityToJobUser ${err}`) }) } function emitCommentEvent(user) { jobUser = user let comment = { userId: saveJob.userId, room: saveJob.room, comment: saveComment } comEmit.emit('comment', comment); return res.status(200).json({ message: 'Comment posted successfully' }); } Comment.create(req.body) .then(pushToJob) .then(updateCommentWithJobId) .then(addActivityToUser) .then(addUserToComment) .then(addActivityToJobUser) .then(emitCommentEvent) .catch((err) => { res.status(500).json({ message: 'An error occurred while posting your comment, please try again' }) }) } 

这是我的一个API的控制器,每次有人发表评论时,我都会发布comment事件。 问题是同一个事件被多次触发。 行console.log('about to emit comment')被触发一次。

我试图寻找一个解决scheme,但没有find任何答案。

什么可能是这种行为的原因?

编辑:这是事件的侦听器。

  socketio.on('connection', function(socket){ Chat.find({}) .then((data)=>{ //Some independent socket events comEmit.on('comment', (data) => { console.log('comment posted ', data) if (userId === data.userId) { socket.join(data.room); } socket.in(data.room).emit('commentPosted', data.comment) }) }) }) 

正如我可以检查日志, 'comment posted'被logging多次,数据是相同的。

我会把我的意见作为一个答案。

在你的socketio.on('connection', ...)处理程序中,你正在做:

 comEmit.on('comment', (data) => { ...}); 

由于只有一个comEmit对象,这意味着每个传入的socket.io连接都会导致为comment事件添加新的重复事件处理程序。 所以,你实际上并没有像你想的那样得到重复的事件,但是有重复的事件处理程序。 所以,当comment事件被触发时,你会得到多个重复的事件处理程序,这个事件都在运行。

解决scheme通常是静态添加事件处理程序,只要在任何请求处理程序之外设置对象时,您就可以添加一个事件处理程序,这样您就不会得到重复的内容,但是具体怎么做取决于整个代码上下文以及您正在尝试的内容从我们所见过的有限的代码中,我不完全遵循。