To replace callbacks with promises in Node.js, we use the util.promisify
method.
For instance, we write
const util = require("util");
const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);
exports.getUsersAsync = async () => {
await connectAsync();
return queryAsync("SELECT * FROM Users");
};
to call util.promisify
with the connectAsync
and queryAsync
methods to convert them to functions that return promises.
And then we call connectAsync
to return a promise and use await
to run the promise.