Convert your callback functions to javascript promise

Santiago Quinteros - CEO & CTO - Software on the road
By:
Santiago Quinteros

But what is Javascript Promise object and why you need to use it?

If you abuse of callback, you will fall in an anti-pattern, "callback hell" seen in code of programmers who are not wise in the ways of asynchronous programming.

getUser(userId, function(err, user){
   getProduct(productId, function(err, product){
      createOrder(user, product, function(err, order){
                ...// Welcome to callback hell
       });
    });
});

The promise approach

getUser(userId)
 .then(user => {
   return getProduct(user)
     .then(product => {
       return createOrder(user, wallet, product)
   })
 })
.catch(err => { 
  console.log('Woops!') 
})

By using the following code snippet, you will be able to use javascript promise with callback style functions.

You don't need any external library, in fact, you only need 13 lines of code.

// Needs spread operator (... notation)
const promisify = (fn) => {
  return (...args) => {
    return new Promise((resolve, reject)=>{
      fn(...args, function(err, res){
        if(err){
          return reject(err);
        }
        return resolve(res);
      })
    })
  }
}
// Polified version
"use strict";
var promisify = function promisify(fn) {
  return function () {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return new Promise(function (resolve, reject) {
      fn.apply(undefined, args.concat([function (err, res) {
        if (err) {
          return reject(err);
        }
        return resolve(res);
      }]));
    });
  };
}; 

Now go and "promisify" all your javascript callback functions

Get the latest articles in your inbox.

Join the other 2000+ savvy node.js developers who get article updates. You will receive only high-quality articles about Node.js, Cloud Computing and Javascript front-end frameworks.


santypk4

CEO at Softwareontheroad.com