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

91
Views
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 answers
Answer question

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