Thursday 13 April 2017

Could this code cause race condition in Node.js?

I'm working in Sails.js, and one of my actions in the controller looks like:

create: function(req, res){

    var comment = req.body;

    var image_id = req.params.id;

    Image.findOne(image_id).populate('comments').exec(function(err, image){


        image.messages.add(comment);

        image.save(function(err){

            return res.created(comment);

        });
    });
}

(Error handling was ommited)

Basically this adds a comment to an image. First, I need to get the image, with it's comments, add the new comment to the array, and save it again.

However, my intuition is that there's a case when two different people try to add a comment, and the order of events is:

  1. Request #1 does findOne() and becomes blocked
  2. Request #2 does findOne() and becomes blocked
  3. Request #1 adds a comment, executes save() and becomes blocked
  4. Request #2 adds a comment, executes save() and becomes blocked

Can this happen in Node.js?, or is there something that prevents this from happening?

I've seen some examples in the website, like http://sailsjs.com/documentation/reference/waterline-orm/populated-values/add where they do something similar. If race condition can happen, then Sail.js becomes completely unuseable for me.

Thanks in advance.



via Felo Vilches

No comments:

Post a Comment