Search code examples
postgresqlasynchronousunderscore.jsnode-postgres

Async pg-node query execution on object's array


I have an object's array which I need to iterate through, and insert each item into the DB (postgres). I'm using _.each in order to iterate through the array.

arr = [ 
      {name: 'Aaron',    description: 'First'},
      {name: 'Brian',    description: 'Second'},
      {name: 'Chris',    description: 'Third'}
]

    var i = 0;
    _.each(array, function(lt){     
        var client = new pg.Client(self.getConnString());
        client.connect(function(err) {
            if (err) {
                          //doSomething//
            }
            var sql = 'insert into load_test (name,description) values(\''+lt.name+'\', \''+lt.description+'\')';
            console.log(i + " <- query: " + lt.name + " desc: " + lt.description);
            query = client.query(sql);
            query.on('end', client.end.bind(client));
            i++;
        });
    });//each

How can I write this function (_each) in the way that it will be async for each query execution?

Thanks


Solution

  • Finally, the solution looks like this :

    self.InsertLT = function(index, callback){
            var client = new pg.Client(self.getConnString());
            if (index < arr.length){
                //console.log('index = ' + index);
                var sql = 'insert into table (name,description) values(\''+arr[index].name+'\', \''+arr[index].description+'\')';
                //console.log(sql);
                client.connect(function(err) {
                    if (err) { 
                        logger.error(self.ERR_CONNECT_TO_DB + ' --> ' + err);
                        callback(-1);    
                    }   
                    client.query(sql, function(err, result){    
                        if (err){    
                            logger.error(self.ERR_RUNNING_QUERY + ' --> ' + err);    
                            callback(-1);    
                        }    
                        else{
                            client.end();
                            self.InsertLT(++index,callback);
                        }
                    });//query
                });
            }
            else{
                callback();
            }