sql - 多次请求后 NodeJS 无限期挂起

标签 sql node.js postgresql asynchronous callback

我有一个连接到 postgres 数据库(node-postgres 模块 v2.1.0)的 nodeJS(v.0.10.23) 代理,以及返回各种 json 数据的 pgpool-II。

过去,这是处理连接错误的方式:

var after = function(callback) {
    return function(err, queryResult) {
        if(err) {
            response.writeHead(500, _header);
            console.log("ERROR: 500");
            console.log(err);
            return response.end(JSON.stringify({error: err}));
        }
        callback(queryResult)
    }
};

基本上它的作用是在没有错误的情况下使用响应。

可以在这里找到深入的解释:Node js - http.request() problems with connection pooling

使用上面的函数,我得到了这样的东西:

pg.connect(_conString, after(function(err, client, done) {
  client.query(sql, after(function(result) {
  ...
  done();
} 

由于当函数被传递到 after() 回调时上下文丢失,我失去了使用 pg.connect() 传递的固有 done() 方法的能力。

删除 after 解决了这个问题,但是,在适当的时候并且有相当数量的客户端拉取数据时, Node 将挂起直到它被重置。

是否有不同的方式来消费各种异步响应?

或者也许是一种将 pg.connect 上下文传递到回调中的方法?

最佳答案

好吧,您当然会丢失 done(),您永远不会在 after() 函数中将第三个参数传递给回调。

function after(cb) {
    return function() {
        // you're using this function in a context where the arguments
        // passed in could be anything. the only constant is that the first
        // argument is the error, if any
        if (arguments[0]) {
            response.writeHead(500, _header);
            console.log("ERROR: 500");
            console.log(err);
            return response.end(JSON.stringify({error: arguments[0]}));
        }
        // apply the entire argument list to the callback, without modification
        cb.apply(cb, arguments);
    };
}

...这也修复了通过 queryResult 变量传递 client 的可疑约定。

关于sql - 多次请求后 NodeJS 无限期挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217743/

相关文章:

javascript - 如何从 Node.js 启动桌面应用程序?

javascript - Cordova hooks,获取项目名称

postgresql - 如何在 Sequelize 中创建这种关系

sql - 获取继承表的父名称和架构

node.js - 使用 babel 推迟导入

python - 如何在 SQLAlchemy 中使用 postgres 数字范围

mysql - 是否有任何 SQL 前端显示子数据表?

mysql - 在同一查询中重用计算字段

sql - 按列联合两个查询结果

sql - 在调试期间观察 SSIS 中的变量