Easiest way to make any callback function as async/await

jbalak
2 min readMar 9, 2020
async await in javascript

A callback in javascript is a function we pass as an argument to any function to handle asynchronous behaviour of javascript. Best way to deal with asynchronous javascript. But then, as always any coin always has two sides,a dark and a bright (I mean heads and tails of course).

Callbacks are awesome but they look weird when there is so much of asynchronous code we have to write and we end up in callback hell. Which is not a good way to write code in javascript.

So then we introduce async/await in javascript and that solves everything. With promises we can write neat and clean code. But here is a thing

Not every function in javascript supports promises. Some libraries still uses old callback functionalities. We can not do anything about them right??

Or can we??

I mean yes we can by creating custom promises around them we can create async await behaviour in our code but let just say we don’t want to use promises then what??

Well there is some utilities in nodejs that help us to convert callback functions to async await functions.

And that utility is util in nodejs

For example wecan look below code

A simple callback function of fs module in nodejs to write json file in file system. Sure we can use fs.writeFileSync() instead of fs.writeFile(). But lets just assume we don’t have fs.writeFileSync() yet in market.

In his above code util.promisify() function takes any function that supports callback and convert it in to async await functions.

This way you not only converts callback into async await but your can avoid callback hell type of situations and get freedom to use any function as async await by ditching callbacks

--

--

jbalak

Hello this is Balkrushna Jadhav. I am just trying to write something to get some attention.