DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

VIGNESH RAVICHANDRAN
VIGNESH RAVICHANDRAN

Posted on

A way to avoid callback hell for functions from older modules:

We can use async and await to avoid callback hells but when we are using any functions from older modules that use callbacks we could use some workarounds to avoid using callbacks. One such workaround is using deferred objects from the module q. The q module has a lot of methods to deal with promises but let’s just focus on how to avoid callbacks.

Let’s see an example

In node when we read files using the fs module the old way of using it was to use callbacks

const fs=require("fs");

fs.readFile("content.txt","utf-8",(err,data)=>{

    if(err){
        console.log(err);
        return;
    }
    console.log(data);
})

Now if we don’t want to use callbacks for this kind of functions we can make use of modules like q

const fs=require("fs");

Require the module

const q=require("q");

Create a deferred object and in place of the callback use the method makeNodeResolver and then we can return the deferred object as a promise.

function readfile(){

  let deffered=q.defer();

 fs.readFile("content.txt","utf-8",deffered.makeNodeResolver())
  return deffered.promise;

}

And then we can use those promises just like any other promises.

readfile().then(function(data){

    console.log(data);
})

Or with async-await

var readfile2=async ()=>{
    const text= await readfile();
    console.log(text)
}

readfile2();

The q module has very good documentation and a lot of ways to handle functions that return promises. Do check it out.

There are a lot of other ways just wanted to share this one too.

Top comments (0)

🌚 Life is too short to browse without dark mode