我有一个需要遍历的对象数组,并将每个项目插入数据库(postgres)。我正在使用_.each
以遍历数组。
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
我怎样才能编写这个函数(_each
)以使其对每个查询执行都是异步的?
谢谢