I use promisifyAll to the following module since I want to use it with promises and I got error "TypeError: Cannot read property 'then' of undefined"
const DBWrapper = Promise.promisifyAll(require("node-dbi").DBWrapper);
var dbWrapper = new DBWrapper('pg', dbConnectionConfig);
dbWrapper.connect();
dbWrapper.insert('USERS', data, function (err, data) {
if (err) {
console.log("error to insert data: " + err);
} else {
console.log("test" + data);
}
}).then(() => {
//read data
dbWrapper.fetchAll("SELECT * FROM USERS", null, function (err, result) {
if (!err) {
console.log("Data came back from the DB.", result);
} else {
console.log("DB returned an error: %s", err);
}
dbWrapper.close(function (close_err) {
if (close_err) {
console.log("Error while disconnecting: %s", close_err);
}
});
});
})
You have two things going on here that are incorrect from what I can tell.
.then()
. If an error occurs they will pass that to the nearest .catch()
. If there is no .catch()
and an error occurs, an unhandledRejection
error will be thrown.promisifyAll()
appends the suffix Async
to any promisified methods, so you will need to modify any method calls on dbWrapper
accordingly.Assuming node-dbi
can be promisifed and that your DB calls are correct the following code should work as you were initially anticipating
const Promise = require('bluebird');
const DBWrapper = require("node-dbi").DBWrapper;
const dbWrapper = Promise.promisifyAll(new DBWrapper('pg', dbConnectionConfig));
return dbWrapper.insertAsync('USERS', data)
.then((data) => {
console.log("test" + data);
//read data
return dbWrapper.fetchAllAsync("SELECT * FROM USERS", null)
})
.then((result) => {
console.log('Data came back from DB.', result);
return dbWrapper.closeAsync();
})
.catch((err) => {
console.log('An error occurred:', err);
});