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

92
Visualizações
How can I trigger another action after one action using Nodejs or Mongoose?

I am using the code below. But setTimeout is not working. What I want to do is; Adding +1 to live_users when a user is live and subtracting -1 after two seconds. Please share with me if there is an easier way to do this (Nodejs, MongoDB or JS).

app.get("/api/user/status", (req, res) => {

    // add +1 to live users.
    Status.findOne()
        .then((live_result) => {
            const new_live_result = live_result['live_users'] + 1
            Status.findByIdAndUpdate(live_result['_id'], { live_users: new_live_result }, { new: true })
                .then((result) => {
                    res.send(result)
                })
                .catch((err) => {
                    res.send(err)
                })

        })

    //After 2 seconds, -1 is subtracted from live users.    
    setTimeout(() => {
        Status.findOne()
            .then((live_result) => {
                const new_live_result = live_result['live_users'] - 1
                Status.findByIdAndUpdate(live_result['_id'], { live_users: new_live_result })

            })
    }, 2000);

})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

if you are new to javascript, I strongly suggest you to learn es6 with async/await flows. imho this way you will be able to learn quicker.

here is a sample solution for you:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

app.get("/api/user/status", async (req, res) => {

    await Status.update({}, { $inc: { live_users: 1 } })
    await sleep(2000);
    await Status.update({}, { $inc: { live_users: -1 } })

})
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