我对nodejs非常新手,我正在将generic-pool与mariasql一起使用。一切正常。但是我将我的代码移到了这样的函数中,我不确定nodejs的事件处理方式是什么,以便我实际上可以从函数中获取结果
var pooledQuery = function (query) {
var result;
//return here will be the return value of pool.acquire
pool.acquire(function(err, client) {
var db;
if (err != null) {
console.log(err)
return err;
}
result = [];
db = client.query(query);
db.on('result', function(res) {
return res.on('row', function(row) {
console.log(row);
return result.push(row);
}).on('error', function(err) {
console.log('error');
}).on('end', function(info) {
return result;
});
}).on('end', function() {
pool.release(client);
return result; <-- i want to know how i can obtain this return value outside of this function??
});
});
//since pool.acquire is non-blocking the code will reach here and return an empty value
return result;
};
nodejs 能够使用上面的函数完成类似事情的方式是什么
var result = pooledQuery("SELECT foo, bar FROM foobar");
我正在使用来自nodejs的通用池https://github.com/coopernurse/node-pool
最佳答案
返回 promise
var pooledQuery = function(query) {
return new Promise(function(resolve, reject) {
//return here will be the return value of pool.acquire
pool.acquire(function(err, client) {
var db;
if (err != null) {
reject(err); // oh no! error, let the promise know that it failed
}
result = [];
db = client.query(query);
db.on('result', function(res) {
return res.on('row', function(row) {
console.log(row);
return result.push(row);
}).on('error', function(err) {
reject(err) // here too
}).on('end', function(info) {
return result;
});
}).on('end', function() {
pool.release(client);
resolve(result); // your promise is resolved,
// any ".then" callback applied to it will be called now.
// i.e `pooledQuery(query).then(function(result){console.log(result)})
});
});
}
};
像这样使用
pooledQuery("SELECT foo, bar FROM foobar").then(function(result){console.log(result);})
有很多 promise 库。 Examples using bluebird
关于javascript - 通用池函数返回回调结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31868844/