Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda