Home > Software engineering >  Semaphore NodeJS endless loading page
Semaphore NodeJS endless loading page

Time:03-27

i'm writing a program that when a client joins to "/json", it gives you a json. I want to adjust this with a semaphore where 1 client per time requests the resource and if it's changed, then it gives to you. I'm using a package in npm called "semaphore" (https://www.npmjs.com/package/semaphore).

kasRouter.get(path   '/json',(req,res)=>{
    sem.take(async () => {
        let toggle2 = await utils.getToggleKas()
        console.log(req)
        if(toggle2 != toggle){
            sem.leave()
            toggle = toggle2
            console.log(toggle)
            res.json({
                'kas':toggle
            })
        }
    })
})

as you can see, when the client joins in the path, i use sem.take() function to let the client wait for leaving it. toggle and toggle2 are basically 2 vars that take a boolean in the json (in a database). When the main route starts the first toggle gets the boolean and when the client joins in the json path waits for toggle chages. The problem in this code is that client tries infinit endlessly to connect in the page but without a response from the server.

CodePudding user response:

Ok, you seem to be missing some things. Namely, you don't call res.end and sem.leave is only called if the result from await utils.getToggleKas() changes

See if the code snippet below helps

kasRouter.get(path   '/json',(req,res)=>{
    sem.take(async () => {
        let toggle2 = await utils.getToggleKas()
        console.log(req)
        if(toggle2 != toggle){
            toggle = toggle2
            console.log(toggle)
            res.json({
                'kas':toggle
            })
        }
        sem.leave() //after every requests, leaves it for a new one
    })
    //res.end() //ends the request in case this doesn't happen elsewhere
    //see if commenting this out ends the problem?
})
  • Related