node.js - Concurrent request handling in Nodejs -
i have issue of concurrent request, modifies db.
what doing is. 1 request fetch data user-1 , calculate data user-1 modified field-1 in record, , save.
next request fetch data user-1 , calculate data user-1 modified field-1 in record, , save.
both request operates simultaneously. last request update wrong data.
function calculate() { var needupdate = false; user = new userlib(user_id); var old_config = user.config; if (old_config[req.id]) { old_config[req.id].value = 0; needupdate = true; } if (req.delete == void(0) || req.delete == false) { delete req.delete; old_config[req.id].value = old_config[req.id].value + 1; needupdate = true; } if (needupdate) { return user.save(); } return true; }
we getting both requests @ same time.
var express = require('express'); var app = express(); app.get('/update', function(req, res) { res.writehead(200, { 'content-type': 'text/html' }); calculate(req); function calculate(req) { var needupdate = false; user = new userlib(user_id); var old_config = user.config; if (old_config[req.id]) { old_config[req.id].value = 0; needupdate = true; } if (req.delete == void(0) || req.delete == false) { delete req.delete; old_config[req.id].value = old_config[req.id].value + 1; needupdate = true; } if (needupdate) { user.save(); } } res.end('done'); }); first reuest following parameter { user_id: 1, id: 1, value: 5, delete: false } anothere request follwing parmter { user_id: 1, id: 1, delete: true }
if want operate on each request simultaneously, i'd suggest use bluebird.map
can handle each request want, concurrency, , final result.
for example:
let users = ['foo', 'bar']; //fetching users want bluebird.map(users, (user) => { return user.calculate() .then((res) => res.shouldupdate ? user.save() : promise.resolve()) }, {concurrency: 2}) .then((results) => { //results array both resolved promises below })
you may interested in bluebird.join
calculate, , join resulting data more 1 promise.
second example fetch same user twice in same promise:
//both promises bluebird.all([fetchuser1, fetchuser2]) .spread(function(user1, user2) { //check if should update return user1.delete !== user2.delete ? user.delete() : null }) .then(() => {})
Comments
Post a Comment