Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Nodejs async overwriting values with knex

I am trying to save multiple records in database using async but I always end up in one record overwriting others.

Here is my logic:

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

My problem is that even using async, the code is not waiting for first record to save and then saves next. The result of above code in database table is:

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

expected output is:

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

I tried to use async.waterfall but received the same error. I don't know how to use synchronize module.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Why don't you save your data by one shot -i.e

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
   })
over 4 years ago · Santiago Trujillo Relatório

0

I solved this problem by changing async.each to async.eachSeries like this:

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

eachSeries is same as each but runs only a single async operation at a time.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda