How to promisify node.js callback functions

Published on

Node came out before await/async and promises, and a lot of its internal tools use callbacks like this:

const fs = require('fs')

function run() {
  fs.readFile('./hello.txt', (err, data) => {
    if(err) throw new Error('something went wrong');
    
    console.log("Success!", data)
  })
}

run()

We can easily turn this into using promises by promisifying it. There are multiple libraries out there, but we can easily do it by hand.

Here is a small example. You just have to use the callback (err, data) => {...} to call the resolve() or reject() promise argument.

const fs = require('fs')

function asyncReadFile(filename) {
  return new Promise((res, rej) => {
    fs.readFile(filename, (err, data) => {
      if(err) rej(err)
      res(data)
    })
  })
}

async function run() {
  try{
    const data = await asyncReadFile(filename);
    console.log("Success!", data)
  }
  catch(error){
    throw new Error('something went wrong');
  }
}

run()

Use the new built in promises

You can also use the built in promises API (since node v10)

const fsPromises = require('fs').promises

async function run() {
    const data = await fsPromises.readFile(filename)
    console.log("Success", data)
}

Read more about the promises API at the official docs