我有一个需要更新的对象列表
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}});
})
}
});
现在的问题是 Node 在循环完成之前继续执行。这意味着如果我在末尾添加 res.status(200).send('ok')
,我无法确定所有内容都已更新。
我的问题是,在向客户发送响应之前,如何确保更新已完成?
最佳答案
使用异步
功能。
// 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();
}
);
为了更好地理解,您可以谷歌搜索异步 js 教程
关于javascript - sequelize (SQL) 等待数组更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40511338/