I have a simple node module which connects to a database and has several functions to receive data, for example this function:
dbConnection.js:
import mysql from 'mysql';
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'db'
});
export default {
getUsers(callback) {
connection.connect(() => {
connection.query('SELECT * FROM Users', (err, result) => {
if (!err){
callback(result);
}
});
});
}
};
The module would be called this way from a different node module:
app.js:
import dbCon from './dbConnection.js';
dbCon.getUsers(console.log);
I would like to use promises instead of callbacks in order to return the data.
So far I've read about nested promises in the following thread: Writing Clean Code With Nested Promises, but I couldn't find any solution that is simple enough for this use case.
What would be the correct way to return result
using a promise?
When setting up a promise you take two parameters,
resolve
andreject
. In the case of success, callresolve
with the result, in the case of failure callreject
with the error.Then you can write:
callback
will be called with the result of the promise returned fromgetUsers
, i.e.result
Below code works only for node -v > 8.x
I use this Promisified MySQL middleware for Node.js
read this article Create a MySQL Database Middleware with Node.js 8 and Async/Await
database.js
You must upgrade node -v > 8.x
you must use async function to be able to use await.
example:
Node.js version 8.0.0+:
You don't have to use bluebird to promisify the node API methods anymore. Because, from version 8+ you can use native util.promisify:
Now, don't have to use any 3rd party lib to do the promisify.
Using the Q library for example:
With bluebird you can use
Promise.promisifyAll
(andPromise.promisify
) to add Promise ready methods to any object.And use like this:
or
Adding disposers
Bluebird supports a lot of features, one of them is disposers, it allows you to safely dispose of a connection after it ended with the help of
Promise.using
andPromise.prototype.disposer
. Here's an example from my app:Then use it like this:
This will automatically end the connection once the promise resolves with the value (or rejects with an
Error
).Using the
Promise
classI recommend to take a look at MDN's Promise docs which offer a good starting point for using Promises. Alternatively, I am sure there are many tutorials available online.:)
Note: Modern browsers already support ECMAScript 6 specification of Promises (see the MDN docs linked above) and I assume that you want to use the native implementation, without 3rd party libraries.
As for an actual example...
The basic principle works like this:
resolve
andreject
This might seem like a lot so here is an actual example.
Using the async/await language feature (Node.js >=7.6)
In Node.js 7.6, the v8 JavaScript compiler was upgraded with async/await support. You can now declare functions as being
async
, which means they automatically return aPromise
which is resolved when the async function completes execution. Inside this function, you can use theawait
keyword to wait until another Promise resolves.Here is an example: