promisify: use promisif instead of callback

React Nathan Krasney
2 min readDec 10, 2020

Motivation

The following code is using a callback function with two arguments :

  • the first is passed on an error
  • the second on success.

This code is working, but the callback function makes it a bit hard to understand. Also, what if you want to return the buffer to the caller?

server1.js — use callback function

What is promisify

promisify is a function of the core node module utils.

promisify solve the above issues as follows :

promisify accept a callback function (err, value) as an argument and return a promise. This promise can be used in an elegant and easy to understand way with async\await as follows

server2.js — use promisfy

Conclusion

I strongly recommend using promise\promisify instead of (err, value) callback function, because it makes the code easy to understand and easy for unit tests.

The only exception to this recommendation is when you can use fs.promises

the code is here

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

React Nathan Krasney
React Nathan Krasney

Written by React Nathan Krasney

25+ years developing software. Lead web instructor & mentor. Focused in last few years on React. Check more info in www.nathankrasney.com

No responses yet

Write a response