最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

节点在插入之前关闭数据库连接或根本不关闭

运维笔记admin18浏览0评论

节点在插入之前关闭数据库连接或根本不关闭

节点在插入之前关闭数据库连接或根本不关闭

我有以下代码执行以下操作:

  • 打开数据库连接(使用pg)。
  • 致电Twitter Trends API(不同地点一次或多次)。
  • 浏览趋势项并将每个项存储到数据库中。
  • 关闭数据库连接。

我尝试了一个直接的代码。我先遇到以下错误。

Error: Connection terminated by user

这是代码。

client.connect();

const text = 'INSERT INTO TRENDS(AS_OF, location_name, name, tweet_volume, rank) VALUES($1, $2, $3, $4, $5) RETURNING *';

T.get('trends/place', { id: 2295424 }, function(err, data, response) {
    data_json = data[0];
    var rankNum = 0;
    console.log(data_json.locations[0].name);
    for (var item of data_json.trends) {
        rankNum++;
        var values = [data_json.as_of, data_json.locations[0].name, item.name, item.tweet_volume, rankNum];
        client.query(text, values)
            .then(res => {
                console.log(res.rows[0])
            })
            .catch(e => console.error(e.stack));
    };
    client.end();
});

看来,在client.end()可以运行之前,数据库连接(client.query())被调用并关闭。所以,我重写了我的代码,等待client.query完成,然后使用async / await调用client.end。

client.connect();

const text = 'INSERT INTO TRENDS(AS_OF, location_name, name, tweet_volume, rank) VALUES($1, $2, $3, $4, $5) RETURNING *';

T.get('trends/place', { id: 23424848 }, function (err, data, response) {
    data_json = data[0];
    var rankNum = 0;
    console.log(data_json.locations[0].name);

    function insRows(){
    return new Promise( resolve => {
        for (var item of data_json.trends) {
        rankNum++;
        var values = [data_json.as_of, data_json.locations[0].name, item.name, item.tweet_volume, rankNum];
        client.query(text, values)
            .then(res => {
                console.log(res.rows[0])
            })
            .catch(e => console.error(e.stack));
        };
    });
    };

    async function closeDBConnection(){
        const a = await insRows();
        client.end();
        return 0;
    };

    closeDBConnection().then( v => {
         console.log(v);
    });
});

这个带有async / await的代码运行正常,但是数据库连接没有关闭,节点只是挂起来转向CTRL + C.

  • 现在版本:vya.2.1
  • 我使用命令运行程序:node app.js

更新1

使用Promise数组和async / await更新了代码。这不起作用:

client.connect();

const text = 'INSERT INTO TRENDS(AS_OF, location_name, name, tweet_volume, rank) VALUES($1, $2, $3, $4, $5) RETURNING *';
T.get('trends/place', { id: 23424848 }, function(err, data, response) {
    const data_json = data[0];
    let rankNum = 0;
    const queryPromises = [];
    console.log(data_json.locations[0].name);
    async function insRows() {
        for (let item of data_json.trends) {
            rankNum++;
            const values = [data_json.as_of, data_json.locations[0].name, item.name, item.tweet_volume, rankNum];
            queryPromises.push(client.query(text, values)
                .then(res => console.log(res.rows[0]))
                .catch(e => console.error(e.stack)));
        };
    };

    (async = () => {
        await Promise.all(queryPromises);
        client.end();
    });
});

我也尝试过:

    async function insRows(){
     /* same as above*/
    }
    await Promise.all(queryPromises);
    client.end();

我收到以下错误(node app_ans.js):

        await Promise.all(queryPromises);
        ^^^^^

SyntaxError: await is only valid in async function
回答如下:

你的代码永远不会调用你创建的承诺的resolve,但是你不需要创建自己的承诺,因为client.query已经返回了一个承诺。我会这样写:

const data_json = data[0];
let rankNum = 0;
const queryPromises = [];

for (let item of data_json.trends) {
    rankNum++;
    const values = [data_json.as_of, data_json.locations[0].name, item.name, item.tweet_volume, rankNum];
    queryPromises.push(client.query(text, values)
        .then(res => console.log(res.rows[0]))
        .catch(e => console.error(e.stack)));
};
await Promise.all(queryPromises);
client.end();
发布评论

评论列表(0)

  1. 暂无评论