6

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 モジュールの例を調べましたが、何か違うことをしていることに気付きませんでした…</p>

4

1 に答える 1

19

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();
                }
            });        
    }
});
于 2013-06-27T07:13:58.240 に答える