Note that there are some explanatory texts on larger screens.

plurals
  1. PODealing with NodeJS asynchronous behavior
    primarykey
    data
    text
    <p>Using NodeJS with MongoDB+Mongoose.</p> <p>First of all, I know the advantages of async non-blocking code. So I do deal with callbacks. But finally I faced the following problem.</p> <p>Lets say I have a function which can be called by user any time. And it is possible, that a super "lightning-speed" user call it twice almost at the same time.</p> <pre><code>function do_something_with_user(user_id){ User.findOne({_id:user_id}).exec(function(err,user){ // FIND QUERY // Do a lot of different stuff with user // I just cannot update user with a single query // I might need here to execute any other MongoDB queries // So this code is a set of queries-callbacks user.save() // SAVE QUERY }) } </code></pre> <p>Of course it executes like this: FIND QUERY, FIND QUERY, SAVE QUERY, SAVE QUERY</p> <p>This totally breaks the logic of an app (should FIND QUERY, SAVE QUERY, FIND QUERY, SAVE QUERY). So I decided to prevent asynchronous behavior by "locking" the whole function for particular user (so inside the function code is still async).</p> <pre><code>var lock_function_for_user = {} function do_something_with_user(user_id){ if(!lock_function_for_user[user_id]){ lock_function_for_user[user_id] = true User.findOne({_id:user_id}).exec(function(err,user){ // Same code as above user.save(function(){ lock_function_for_user[user_id] = false }) }) } else { setTimeout(function(){ do_something_with_user(user_id) },100) // assuming that average function execution time is 100ms in average } } </code></pre> <p>So, my question is: is it a good practice, good hack or bad hack? If it is a bad hack, please provide any other solution. Especially, I doubt this solution will work when we scale and launch more than one NodeJS processes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload