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

Converting Callbacks to Promise approach on Node.js

gabrielrufino profile image Gabriel Rufino ・1 min read

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)
  }
})

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)
  })

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 */)

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)
  }) 

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

Posted on by:

gabrielrufino profile

Gabriel Rufino

@gabrielrufino

Fullstack Developer around JavaScript stack. Solving problems, generating value!

Discussion

markdown guide