drekka
drekka

Reputation: 21903

Node/MySQL2/bluebird promises not working

I have the following code:

var Promise = require('bluebird');
var mysql = require('mysql2/promise');

var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'crux'
});

Database.prototype.listProjects = function () {
    return getConnection()
        .then(function (connection) {
            return connection.query('SELECT * FROM project');
        })
};

function getConnection() {
    return pool.getConnection().disposer(function (connection, promise) {
        connection.release();
    });
}

But when I run this I get this error:

TypeError: pool.getConnection(...).disposer is not a function
    at getConnection (...
    at Database.listProjects(...
    .... 

I've been trying to follow the sample code on the MySQL2 github site. But I cannot see why this is not working. pool.getConnection() seems to be returning a promise as far as I can tell.

Anyone done code like this?

Upvotes: 0

Views: 2083

Answers (2)

Andrey Sidorov
Andrey Sidorov

Reputation: 25466

If you prefer bluebird version of promises you can pass it as a parameter to mysql2:

var Promise = require('bluebird');
var mysql = require('mysql2/promise');

var pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'crux',
  Promise: Promise
});

See https://github.com/sidorares/node-mysql2/blob/c487f542f7f4416f9759319225197c383b4937fb/promise.js#L5

By default global Promise is used, but just doing var Promise = require('bluebird'); does not make it global.

Upvotes: 3

drekka
drekka

Reputation: 21903

Thanks everyone. I've now switched over to the Knex API which solves all the problems I was encountering.

Upvotes: 2

Related Questions