How to correctly implement an asynchronous counter in Node.js?

Asked

Viewed 121 times

2

I am experiencing difficulties in implementing an asynchronous counter using Node.js and Mongodb.

Follows the code:

app.get('/', req, res ()=> {
var number = await Number.find({}); // Leitura do valor
number++;                           // Incrementação do valor               
await Number.save(number);          // Salva valor incrementado
res.send(number);                   // Retorna valor para usuário
})             

The question I have is this: It would be necessary to implement a semaphore to accomplish this task without running condition or Node.js handles it automatically?

  • It would be what kind of race condition and what objects involved?

  • This could occur when two or more users access the Uri at the same time.

  • 1

    Nodejs is single thread. Requests are queued, even if two users make the same request simultaneously first it resolves a request and only after its resolution it passes to another user’s request.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.