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. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. Span標簽3. css - 求推薦適用于vue2的框架 像bootstrap這種類型的4. docker-machine添加一個已有的docker主機問題5. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?6. css - 關于div自適應問題,大家看圖吧,說不清7. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。8. angular.js使用$resource服務把數據存入mongodb的問題。9. redis啟動有問題?10. SessionNotFoundException:會話ID為null。調用quit()后使用WebDriver嗎?(硒)
