rel*_*der 2 node.js eventemitter
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' })
})
}
Run Code Online (Sandbox Code Playgroud)
这是我的一个 api 的控制器,comment每次有人对作者的帖子发表评论时我都会发出该事件。问题是同一个事件会被多次触发。该线路console.log('about to emit comment')仅被触发一次。
我尝试寻找解决方案,但尚未找到任何答案。
造成这种行为的原因是什么?
编辑:这是事件的侦听器。
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)
})
})
})
Run Code Online (Sandbox Code Playgroud)
因为我可以检查日志,'comment posted'所以多次记录并且数据是相同的。
我会将我的评论变成答案。
在你的socketio.on('connection', ...)处理程序中,你正在做:
comEmit.on('comment', (data) => { ...});
Run Code Online (Sandbox Code Playgroud)
由于只有一个comEmit对象,这意味着每个传入的 socket.io 连接都会导致您为该事件添加新的重复事件处理程序comment。因此,您实际上并没有像您想象的那样获得重复的事件,而是拥有重复的事件处理程序。因此,当comment事件被触发时,您会得到该事件的多个重复的事件处理程序。
解决方案通常是静态添加事件处理程序,仅在您在任何请求处理程序外部设置对象时添加一次,这样就不会重复,但具体如何执行此操作取决于整体代码上下文和您正在尝试的内容从我们所看到的有限代码中,我不太能理解这一点。
| 归档时间: |
|
| 查看次数: |
3365 次 |
| 最近记录: |