Node.js Nodejs使用knex异步覆盖值
我试图使用async在数据库中保存多条记录,但我总是在一条记录中覆盖其他记录 我的逻辑是:Node.js Nodejs使用knex异步覆盖值,node.js,async.js,knex.js,Node.js,Async.js,Knex.js,我试图使用async在数据库中保存多条记录,但我总是在一条记录中覆盖其他记录 我的逻辑是: 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) .
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;
});
}
我的问题是,即使使用异步,代码也不会等待第一条记录保存,然后再保存下一条记录。数据库表中上述代码的结果是:
emp_id got_bonus
------- ----------
3 true
3 false
3 true
预期产出为:
emp_id got_bonus
------- ----------
1 true
2 false
3 true
我尝试使用async.瀑布,但收到了相同的错误。我不知道如何使用同步模块。为什么不一次保存数据呢
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();
});
每个系列与每个相同,但一次只运行一个异步操作。实际上,逻辑分为多个层