Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda