泛型池函数返回回调的结果
generic pool function return result of callback
我是nodejs的新手,我正在使用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
返回一个承诺
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)})
});
});
}
};
使用like so
pooledQuery("SELECT foo, bar FROM foobar").then(function(result){console.log(result);})
有很多promise库。使用bluebird
相关文章:
- 将web服务回调的结果绑定到Javascript中的调用函数
- 返回循环中调用的回调结果的串联
- 从回调函数返回 AJAX 结果
- MongoDB:$addToSet Meteor中的重复结果回调
- node.js+MySQL;JSON结果-回调问题&没有响应客户端
- 如何通过回调访问nodejs中的mongodb计数结果
- 而循环和回调返回不同的结果
- 如何显示查询回调数据结果仅从开始
- Node.JS- R,Python大量计算识别回调何时返回并存储该结果
- 咖啡脚本化的 ajax 调用结果在实际成功时失败回调
- Meteor.js HTTP.get 获取 JSON 引号并解析结果似乎包含一个回调函数
- 如何使用异步并行将所有回调结果合并到最终回调中
- 根据多个回调结果的结果执行最终回调
- 我是否需要为每个具有等待结果回调的方法关闭
- 我想要一些在另一个回调函数内部的结果
- 使用 AJAX 回调更新挖空可观察数组会生成随机排序的结果
- 为什么我在 JavaScript 中的回调不适用于异步结果
- 为什么异步并行回调会返回意外结果
- 承诺链接:在next-then回调中使用上一个承诺的结果
- Node.js回调错误和结果澄清