callback hell in JavaScript.

callback hell in JavaScript.

What is a callback function?

Function passed to another function as an argument and is invoked inside the outer function to complete a regular action or routine.

A good example would be

function greetings(name) {
   console.log(`Hello ${name}. How are you?`);
}

function getName(callback) {
   var yourname = prompt("Input your name first!");
   callback(yourname);
}

getName(greetings(name));

At times you will find yourself struggling with “callback hell”(commonly referred to as Pyramid of Doom). A situation where your code contains a lot of nested callback functions.

For instance you want to perform actions like add two numbers first, then multiply the result with 100 and then say done after the operation is through in that order.

See example below

function addNums(arg1, arg2, callback) {
   var summedResult = arg1 + arg2;
   console.log("Sum is "+summedResult);
   callback(summedResult);
}

function multiplyNums(arg3, arg4, anotherCallback) {
   var multipliedResult = arg3 * arg4;
   console.log("Multiplication results to "+multipliedResult);
   anotherCallback();
}

function sayDone() {
   console.log("Done! :D")
}

function compute(a, b, adder, multiplier, done) {
   adder(a, b, function(x, y){
       multiplier(x, y=100, function() {
           done();
       })
   });
}

compute(10, 20, addNums, multiplyNums, sayDone);

Using callbacks for the above scenario can be confusing.

So how do we solve this?

The answer is using promises. The Promise represents the eventual completion or failure of an asynchronous operation and its value.

Solution

function addNums(a, b) {
   return new Promise((resolve, reject) => {
       var result = a + b;
       resolve(result);
   })
}

function multiplyNums(sum, num) {
   return new Promise((resolve, reject) => {
       var result = sum * num;
       resolve(result);
   })
}

adds(10, 20)
 .then(result => result)
 .then(sum => multiplier(sum, 100))
 .then(finalResult => console.log(finalResult));

That’s even cool. Right?**

Let me hear your views on callback and promises