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