DEV Community

Cover image for Converting Callbacks to Promise approach on Node.js
Gabriel Rufino
Gabriel Rufino

Posted on

Converting Callbacks to Promise approach on Node.js

A pattern very used at the beginning of Node.js was the Callback pattern. This pattern was the first way to resolve the asynchronism of the javascript single thread.

Look at a fake example below:

function getUserCallback(id, callback) {
  setTimeout(function () {
    callback(null, {
      id,
      name: 'Gabriel Rufino'
    })
  }, 2000)
}

getUserCallback(1234, function (error, user) {
  if (!error) {
    console.log(user)
  }
})
Enter fullscreen mode Exit fullscreen mode

Fortunately, today we have Promises and the lovely duo async/await to treat the asynchronous flow more elegantly.

The same function getUser using Promise:

function getUserPromise(id) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve({
        id,
        name: 'Gabriel Rufino'
      })
    }, 2000)
  })
}

getUserPromise(1234)
  .then(function (user) {
    console.log(user)
  })
  .catch(function (error) {
    console.error(error)
  })
Enter fullscreen mode Exit fullscreen mode

But not everything is perfect. There's a lot of functions or npm packages that work only with the callback approach. Hopefully, the Node.js has built-in util that helps us to transform functions that receive a callback as an argument to a function that returns a Promise.

It's the util.promisify helper:

const util = require('util')

const functionPromise = util.promisify(/* Function here */)
Enter fullscreen mode Exit fullscreen mode

Look at an example of transforming:

const { promisify } = require('util')
const getUserCallback = require('./getUserCallback')

getUserCallback(1234, function (error, user) {
  if (!error) {
    console.log(user)
  }
})

const getUserPromise = promisify(getUserCallback)

getUserPromise(1234)
  .then(function (user) {
    console.log(user)
  })
  .catch(function (error) {
    console.log(error)
  }) 
Enter fullscreen mode Exit fullscreen mode

Important: The function must follow the callback pattern

  1. The callback must be the last argument
  2. The first argument of the callback must be the possible error

That's it! Thank you :D

Top comments (0)