Nodejs 异步用 knex 覆盖值

Nodejs async overwriting values with knex

我正在尝试使用异步在数据库中保存多条记录,但我总是以一条记录覆盖其他记录而告终。

这是我的逻辑:

var deferred = q.defer();

var records = [{emp_id:1, got_bonus: true},{emp_id:2, got_bonus: false},{emp_id:3, got_bonus: true}];

async.each(records, function(record, next){
    saveRecord(record)
      .then(){
          next(null);
      });
}, function(){
    deferred.resolve();
});

function saveRecord(record){
   record['activity_type'] = 'bonus'; 
   db_module.save(record);
}

db_module.js
----------------
function saveRecord(record){
   var deferred = q.defer();

   checkDuplicate(record)
      .then(function(isDuplicate)){
          if(!isDuplicate){
              knex('employees').insert(record);

              deferred.resolve();
          }
      });
   }
}

function checkDuplicate(record){
   return knex('employees')
            .where({'emp_id': record['emp_id']})
            .then(function(rows){
                return rows && rows.length > 0;
            });
}

我的问题是,即使使用异步,代码也不会等待第一条记录保存然后再保存下一条记录。以上代码在数据库 table 中的结果是:

emp_id      got_bonus
-------     ----------
3            true
3            false
3            true

预期输出为:

emp_id      got_bonus
-------     ----------
1            true
2            false
3            true

我尝试使用 async.waterfall 但收到了同样的错误。我不知道如何使用同步模块。

你为什么不通过 one shot - 即

保存你的数据
var records = [
    {emp_id:1, got_bonus: true},
    {emp_id:2, got_bonus: false},
    {emp_id:3, got_bonus: true}
];
var modifiedRecords = records.map((i) => {
    return Object.assign({}, i, {
       activity_type : 'bouns',
    })
});

knex('employees')
  .insert(modifiedRecords)
  .then(()=> {
       /// sent response
   })

我通过将 async.each 更改为 async.eachSeries 解决了这个问题,如下所示:

async.eachSeries(records, function(record, next){
  saveRecord(record)
    .then(){
      next(null);
    });
}, function(){
   deferred.resolve();
});

eachSerieseach 相同,但一次只运行一个异步操作。