Categories
JavaScript Answers

How to replace callbacks with promises in Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *