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
Finally, the solution looks like this :