javascript - sequelize (SQL) 等待数组更新

标签 javascript node.js sequelize.js

我有一个需要更新的对象列表

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/

相关文章:

javascript - jQuery 触发器 ('click' ) 未在复选框上触发 .click 事件

javascript - 如何在 create-react-app 中使用 Sass 和 CSS 模块?

node.js - 如何在 Windows 上安装 MediaWiki Parsoid

node.js - 无法使用 sequelize : 'Column " 0"of relation "users"does not exists' 递增

javascript - 通过单击显示 div 后启动 TwentyTwenty.js

javascript - polymer ,观察全局变量

node.js - 如何在 Node.js 中为请求编码任意字符串?

linux - 自动重启 Node.Js 应用程序

node.js - 有没有办法自动编码 where 子句中的属性,使其与模型 setter (sequelize)匹配?

javascript - Sequelize - 如何包含自定义列详细信息