Node中使用PostgreSQL的异步数据库查询不起作用 [英] Asynchronous Database Queries with PostgreSQL in Node not working

查看:75
本文介绍了Node中使用PostgreSQL的异步数据库查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Node.js和 node-postgres模块与数据库进行通信,我正在尝试编写一个函数,该函数接受查询和回调数组,并使用相同的数据库连接异步执行它们。该函数接受一个二维数组,并调用它,如下所示:

Using Node.js and the node-postgres module to communicate with a database, I'm attempting to write a function that accepts an array of queries and callbacks and executes them all asynchronously using the same database connection. The function accepts a two-dimensional array and calling it looks like this:

perform_queries_async([
  ['SELECT COUNT(id) as count FROM ideas', function(result) {
    console.log("FUNCTION 1");
  }],
  ["INSERT INTO ideas (name) VALUES ('test')", function(result) {
    console.log("FUNCTION 2");
  }]
]);

该函数遍历数组,为每个子数组创建一个查询,如下所示: / p>

And the function iterates over the array, creating a query for each sub-array, like so:

function perform_queries_async(queries) {
  var client = new pg.Client(process.env.DATABASE_URL);

  for(var i=0; i<queries.length; i++) {
    var q = queries[i];

    client.query(q[0], function(err, result) {
      if(err) {
        console.log(err);
      } else {
        q[1](result);
      }
    });
  }

  client.on('drain', function() {
    console.log("drained");
    client.end();
  });

  client.connect();
}

运行上面的代码时,我希望看到如下输出: / p>

When I ran the above code, I expected to see output like this:

FUNCTION 1
FUNCTION 2
drained

但是,输出看起来像这样:

However, the output bizarrely appears like so:

FUNCTION 2
drained
FUNCTION 2

不仅第二个函数同时被调用请求,似乎还需要在客户端的查询队列运行完成之前调用流失代码...但是,即使 client.end()代码表面上杀死了客户端。

Not only is the second function getting called for both requests, it also seems as though the drain code is getting called before the client's queue of queries is finished running...yet the second query still runs perfectly fine even though the client.end() code ostensibly killed the client once the event is called.

我已经为此事花了好几个小时了。我在示例数组中尝试了硬编码(因此删除了for循环),并且我的代码按预期工作,这使我相信我的循环中存在一些我没有看到的问题。

I've been tearing my hair out about this for hours. I tried hardcoding in my sample array (thus removing the for loop), and my code worked as expected, which leads me to believe that there is some problem with my loop that I'm not seeing.

任何可能会发生这种情况的想法都将受到赞赏。

Any ideas on why this might be happening would be greatly appreciated.

推荐答案

最简单的正确方法在现代JavaScript的闭包中捕获 q 变量的值是使用 forEach

The simplest way to properly capture the value of the q variable in a closure in modern JavaScript is to use forEach:

queries.forEach(function(q) {
    client.query(q[0], function(err, result) {
      if(err) {
        console.log(err);
      } else {
        q[1](result);
      }
    });
 });

如果不捕获该值,则代码将反映 q 作为包含函数的上下文,作为稍后执行的回调函数。

If you don't capture the value, your code reflects the last value that q had, as the callback function executed later, in the context of the containing function.

forEach ,通过使用回调函数可以隔离并捕获 q的值,因此可以由内部回调正确评估。

forEach, by using a callback function isolates and captures the value of q so it can be properly evaluated by the inner callback.

这篇关于Node中使用PostgreSQL的异步数据库查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆