Sometimes, we want to replace callbacks with promises in Node.js.
In this article, we’ll look at how to replace callbacks with promises in Node.js.
How to replace callbacks with promises in Node.js?
To replace callbacks with promises in Node.js, we can use the util.promisify
method.
For instance, we write
import mysql from 'mysql';
const util = require('util');
const connection = mysql.createConnection({
host: 'localhost',
user: 'user',
password: 'password',
database: 'db'
});
const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);
const getUsersAsync = async () => {
await connectAsync()
return queryAsync('SELECT * FROM Users')
};
to convert the connection.connectAsync
and connection.queryAstnc
methods to functions that returns promises with util.promisify
.
Then in the getUsersAsync
function, we call them both.
We use await
to wait for the promise returned by connectAsync
to resolve before calling queryAsync
.
Conclusion
To replace callbacks with promises in Node.js, we can use the util.promisify
method.