我有以下简单的节点应用程序用于将数据插入 postgres 数据库:
var pg = require('pg');
var dbUrl = 'tcp://user:psw@localhost:5432/test-db';
pg.connect(dbUrl, function(err, client, done) {
for (var i = 0; i < 1000; i++) {
client.query(
'INSERT into post1 (title, body, created_at) VALUES($1, $2, $3) RETURNING id',
['title', 'long... body...', new Date()],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
});
}
});
在终端中运行 Node app.js 后,它会将 1000 行插入数据库,然后应用程序挂起,并且不会终止。我做错了什么?我查看了 pg 模块示例,但没有发现我正在做任何不同的事情......
我错过了对 client.end() 的调用;现在应用程序正确退出:
pg.connect(dbUrl, function(err, client, done) {
var i = 0, count = 0;
for (i = 0; i < 1000; i++) {
client.query(
'INSERT into post1 (title, body, created_at) VALUES($1, $2, $3) RETURNING id',
['title', 'long... body...', new Date()],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
count++;
console.log('count = ' + count);
if (count == 1000) {
console.log('Client will end now!!!');
client.end();
}
});
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)