Reputation: 20555
I have a list of objects that i need to update
router.route('/api2/user/bulk')
.put(function (req, res) {
if(req.body.users && req.body.fieldKey)
{
req.body.users.forEach(function (x) {
var updateVariable = {};
updateVariable[req.body.fieldKey] = _.get(x, req.body.fieldKey);
model.user.update(updateVariable, {where: {id: x.id}});
})
}
});
Now the problem with this is that node continues to execute before the loop is done. Meaning that i cannot know for certain that all has been updated if i add an res.status(200).send('ok')
at the end.
My question is how can i make sure that the update has gone through before i send a response back to my client?
Upvotes: 1
Views: 76
Reputation: 366
using async
functionality.
// Include the async package
// Make sure you add "async" to your package.json
async = require("async");
// 1st para in async.each() is the array of items
async.each(items,
// 2nd param is the function that each item is passed to
function(item, callback){
// Call an asynchronous function, often a save() to DB
item.someAsyncCall(function (){
// Async call is done, alert via callback
callback();
});
},
// 3rd param is the function to call when everything's done
function(err){
// All tasks are done now
doSomethingOnceAllAreDone();
}
);
for better understanding you may google for tutorials for async js
Upvotes: 1