node.js - version3的generic-pool问题
问题描述
第三版的generic-pool问题,按照里面的example执行的代码,但是很郁闷的是代码不能运行,单步的话,也只是到resourcePromise.then(function(client)就不执行了,这是为什么那?使用的模块地址:https://github.com/coopernurs...全部代码如下:
var genericPool = require(’generic-pool’);var DbDriver = require(’mysql’);/** * Step 1 - Create pool using a factory object */const factory = { create: function(){return new Promise(function(resolve, reject){ var client = DbDriver.createPool({host:’localhost’,user : ’root’,password : ’root’,database : ’world’}); client.on(’connected’, function(){resolve(client) })}) }, destroy: function(client){return new Promise(function(resolve){ client.on(’end’, function(){resolve() }) client.disconnect()}) }}var opts = { max: 10, // maximum size of the pool min: 2 // minimum size of the pool}var myPool = genericPool.createPool(factory, opts);/** * Step 2 - Use pool in your code to acquire/release resources */// acquire connection - Promise is resolved// once a resource becomes availablevar resourcePromise = myPool.acquire();resourcePromise.then(function(client) { console.log(’in ’); client.query('select * from city', [], function(err,result) {console.log(err);console.log(result);// return object back to poolmyPool.release(client); });}) .catch(function(err){// handle error - this is generally a timeout or maxWaitingClients// error });/** * Step 3 - Drain pool during shutdown (optional) */// Only call this once in your application -- at the point you want// to shutdown and stop using this pool.myPool.drain(function() { myPool.clear();});
问题解答
回答1:请参照 mysql 的官方文档:https://github.com/mysqljs/mysql
var mysql = require(’mysql’);var connection = mysql.createConnection({ host : ’localhost’, user : ’root’, password : ’root’, database : ’world’}); connection.connect(function(err) {});
PS: Promise 没有执行可以断定是 resolve 或 reject 没有执行到,这样可以定位到是没有 connected 事件。而且 mysql 库本身带连接池用法的,所以不需要用 generic-pool。附个文章吧:描述问题症状而非你的猜测
回答2:resourcePromise.then 进不去说明 resolve 或 reject 没有执行到 ,这样可以定位到 factory 的 create 中的 resolve(client)没执行,那么再定位到 是不是client.on(’connected’ 没执行呢 ! 接着查一下 mysql.js 的文档 是client.connect(function(err){} 来进行数据库连接的。 所以解决方法是:
var client = require(’mysql’).createConnection({host:’localhost’,user : ’root’,password : ’root’,database : ’world’}); client.connect(function(err){ if(err){console.log(’Database connection error’); }else{esolve(client);console.log(’Database connection successful’); });
相关文章:
1. javascript - 我写的href跳转地址不是百度,为什么在有的机型上跳转到百度了,有的机型跳转正确2. node.js - 微信的自动回复问题3. 微信小程序如何将获取的时间戳提交到数据库?4. python3.x - python中import theano出错5. python - pandas按照列A和列B分组,将列C求平均数,怎样才能生成一个列A,B,C的dataframe6. python - 如何给模块传参数,参数是模块的函数名?7. python - 老铁们,在列表中如何对时间进行排序~8. mysql - 为什么innodb下更新A行时B行也被锁住?9. node.js - nodejs中mysql子查询返回多行结果怎么处理?10. mysql - spring data jpa 方法sql复杂查询?