Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Semaphore NodeJS endless loading page

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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?
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!