2016-11-09 44 views
1

我有我需要更新sequelize(SQL)等待,直到陣列已經更新

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}}); 
     }) 
    } 
}); 

對象的列表現在有了這個問題是該節點將繼續循環完成之前執行。這意味着如果我在最後添加res.status(200).send('ok'),我無法確定所有更新。

我的問題是我怎麼才能確保更新已經通過之前,我發送迴應給我的客戶?

回答

1

使用async功能。

 // 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