我有一个连接到 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/