Categories
JavaScript Answers

How to replace callbacks with promises in Node.js and JavaScript?

Spread the love

Sometimes, we want to replace callbacks with promises in Node.js and JavaScript.

In this article, we’ll look at how to replace callbacks with promises in Node.js and JavaScript.

How to replace callbacks with promises in Node.js and JavaScript?

To replace callbacks with promises in Node.js and JavaScript, we can use the promisfy function from the util module.

For instance, we write

const { promisify } = require("util");
const glob = promisify(require("glob"));

app.get("/", async (req, res) => {
  const files = await glob("src/**/*-spec.js");
  res.render("template-test", { files });
});

to call promisify with the glob function we get from require("glob").

promisify returns a promise if we pass in anything that takes a standard Node.js async callback.

Therefore, we can use await with glob to get the resolve value from the promise.

Conclusion

To replace callbacks with promises in Node.js and JavaScript, we can use the promisfy function from the util module.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.