Skip to content

Instantly share code, notes, and snippets.

@bpceee
Created August 11, 2014 02:24
Show Gist options
  • Save bpceee/e77d32664b97864c9db7 to your computer and use it in GitHub Desktop.
Save bpceee/e77d32664b97864c9db7 to your computer and use it in GitHub Desktop.
pessimistic lock in nodejs
function partial(f) {
var args = Array.prototype.slice.call(arguments, 1)
return function() {
var remainingArgs = Array.prototype.slice.call(arguments)
return f.apply(null, args.concat(remainingArgs))
}
}
var options = {
db: {
safe: true
}
}
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', options);
var ThingSchema = new mongoose.Schema({
count: Number,
});
var Thing = mongoose.model('Thing', ThingSchema);
var lock = true;
var id = "53e5fec1bcb589c92f6f38dd";
var doAdd = function(id){
if(lock == false)
{
setTimeout(partial(arguments.callee, id), 0);
}
else{
lock = false;
Thing.findById(id, function(err, thing){
console.log(thing.count)
thing.count++;
thing.save(function(){
lock = true;
});
});
}
};
doAdd(id);
doAdd(id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment