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

98
Views
¿Cómo puedo desencadenar otra acción después de una acción usando Nodejs o Mongoose?

Estoy usando el código de abajo. Pero setTimeout no funciona. Lo que quiero hacer es; Agregar +1 a live_users cuando un usuario está en vivo y restar -1 después de dos segundos. Comparta conmigo si hay una manera más fácil de hacer esto (Nodejs, MongoDB o 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 answers
Answer question

0

si es nuevo en javascript, le sugiero que aprenda es6 con flujos async/await. En mi humilde opinión, de esta manera podrás aprender más rápido.

Aquí hay una solución de muestra para usted:

 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 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!