神刀安全网

Node.js simple lock mechanism

Lock Node.js simple lock mechanism

Locking mechanism for async functions

Use case

In mongodb you can’t execute two concurrent writes:

app.put('/:id', function(req, res) {   var coll = db.collection('mycoll')   coll.findOne({ _id: req.params.id }, (err, doc) => {     coll.update({ _id: req.params.id }, { count: ++doc.count })   }) })

(note: we could use mongodb $inc operator, but that’s not the point)

If two users call simultaneously this action (with the same ID), only one of both writes would be executed.

By using lock() it’s easy to fix our problem:

app.put('/:id', function(req, res) {   lock(req.params.id, function(next) {     var coll = db.collection('mycoll')     coll.findOne({ _id: req.params.id }, (err, doc) => {       coll.update({ _id: req.params.id }, { count: ++doc.count }, next)     })   }) })

Usage

Basic example:

lock(next => {   setTimeout(() => {     console.log(1)     next()   }, 1000) })  lock(next => {   console.log(2)   next() })  // 1 // 2

You can isolate locks, by using namespaces:

lock('lock1', next => {   setTimeout(() => {     console.log(1)     next()   }, 1000) })  lock('lock2', next => {   console.log(2)   next() })  lock('lock1', next => {   console.log(3)   next() })  // 2 // 1 // 3

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Node.js simple lock mechanism

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址