Using callbacks with async await or promises

 In the modern javascript universe, most of the libraries now support async/await or promise syntax. But there are some libraries that do not support this syntax or you might need to work some of your old which are written using callbacks and you don't want to touch it, but just want to use it. 

Let's take the example of the following code snippet

// filename read-my-file.js

const fs = require("fs");

// Use fs.readFile() method to read the file

function readMyFile(filePath, callback) {
  fs.readFile(filePath, "utf8", function (err, data) {
    if (err) {
      //log error silently or throw error

      callback(err);
    }

    callback(null, data);
  });
}

module.exports = { readMyFile };


let's say now you want to use this readMyFile, what you will need to do is

// filename:  main.js

const fileReader = require("./read-my-file");

function printMyData() {
  fileReader.readMyFile("sample.txt", function (err, data) {
    if (err) {
      throw err;
    }

    console.log(data);
  });
}

printMyData();

 But, let's say you want this readMyFile but all your codebase is promise compliant and you want to keep it that way. What you need to do is to wrap this function inside a new Promise and return it

// filename:  wrapper-read-file.js

const fileReader = require("./read-my-file");

async function readMyFile(filePath) {
  return new Promise((resolve, reject) => {
    fileReader.readMyFile(filePath, function (err, data) {
      if (err) {
        reject(err);
      }
      resolve(data);
    });
  });
}

module.exports = { readMyFile };

Now, you can use this wrapper in your main function instead of the original readMyFile method


// filename: main.js

const fileReader = require("./wrapper-read-file");

async function printData() {
  try {
    const data = await fileReader.readMyFile("sample.txt");

    console.log(data);
  } catch (err) {
    console.log(err);
  }
}

printData();

Comments

Post a Comment