How to promisify a MySql function using bluebird?

ぃ、小莉子 提交于 2019-12-03 08:31:19

I have done this way and it is working fine.

const connection = mysql.createConnection({.....});
global.db  = Bluebird.promisifyAll(connection);
db.queryAsync("SELECT * FROM users").then(function(rows){   
console.log(rows);});

I have never had much luck with promisifyAll and IMO I prefer to handle my internal checks manually. Here is an example of how I would approach this:

//ThingModule
var Promises = require('bluebird');

Things.list = function(params) {
 return new Promises(function(resolve, reject) {
   db.query('SELECT * FROM thing...', function(err, data) {
     return (err ? reject(err) : resolve(data));
   });

 });
}

//usage
var thinger = require('ThingModule');

thinger.list().then(function(data) {
   //do something with data
})
.error(function(err) {
  console.error(err);
})

You can also create a function that fires SQL like this :-

function sqlGun(query, obj, callback) {
    mySQLconnection.query(query, obj, function(err, rows, fields) {
        if (err) {
            console.log('Error  ==>', err);
            // throw err;
            return (err, null);
        }
        console.log(query)
        if (rows.length) {
            return callback(null, rows);
        } else {
            return callback(null, [])
        }
    });

}

Where mySQLconnection is the connection object you get after mysql.createConnection({}).

After that, you can promisify the function and use the promise like below :-

var sqlGunPromise = Promise.promisify(sqlGun);
sqlGunPromise(query, {}).then( function() {} );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!