socket.io emits multiple times

后端 未结 3 1667
天命终不由人
天命终不由人 2021-01-04 06:53

I have got a very basic example. This question has been asked previously multiple times in stack overflow itself but I could not get the right answer so I am going with this

3条回答
  •  别那么骄傲
    2021-01-04 07:29

    I didn't read the question, but I'm putting this on here to help the others, cause I hadn't find this kind of answer yet.

    In my case, I was calling the function next multiple times, just like so

    io.use(async (socket, next) => {
        let req = socket.request
        let res = req.res || {}
    
        someMiddleware()(req, res, next)
        anotherMiddleware({extended: false})(req, res, next)
        anotherMiddleware()(req, res, next)
        anotherMiddleware(req, res, next)
        anotherMiddleware()(req, res, next)
        anotherMiddleware()(req, res, next)
    })
    

    Every time I was calling a middleware, the next function was getting called and on('connection') was being called too. What I got to do was overwrite the next and put it inside the last middleware, so connection get called just once.

    . . .
    let originalNext = next
    next = () => {} // NOW its not going to annoy anymore
    someMiddleware()(req, res, next)
    anotherMiddleware({extended: false})(req, res, next)
    anotherMiddleware()(req, res, next)
    anotherMiddleware(req, res, next)
    anotherMiddleware()(req, res, next)
    anotherMiddleware()(req, res, originalNext) //next get called <
    . . . 
    

提交回复
热议问题