Need help on JS callback hell

Viewed 17

I am challenging myself by writing a simple JavaScript callback hell to grasp the concept without using the widely spread setTimeout function examples on the net. I did something wrong and haven't succeeded yet to nest my callbacks and return the final result.

const multiplication = (a, b) => {
  let multiply = a * b;
  console.log(`${multiply} from multiplication`);
  return multiply;
};
const addition = (multiply, n1) => {
  let add = multiply + n1;
  console.log(`${add} from addition`);
  return division(add);
};
const division = (add) => {
  let div = add / 2;
  console.log(`${div} from division`);
  return div;
};

console.log(
  multiplication(10, 20, () => {
    addition(multiply, 100, () => {
      division(add);
    });
  })
);

1 Answers

If you want to use callbacks, then you'll have to define them as arguments to your functions, and also to call them at the end instead of returning.

Due to how callback control flow works, you won't be able to do

console.log(
  multiplication(10, 20, () => {
    ...

Rather, you'll have to log in the innermost defined callback to get to the final result.

const multiplication = (a, b, callback) => {
  let multiply = a * b;
  console.log(`${multiply} from multiplication`);
  callback(multiply);
};
const addition = (multiplyResult, n1, callback) => {
  let add = multiplyResult + n1;
  console.log(`${add} from addition`);
  callback(add);
};
const division = (add, callback) => {
  let div = add / 2;
  console.log(`${div} from division`);
  callback(div);
};

multiplication(10, 20, (multiplyResult) => {
  addition(multiplyResult, 100, (addResult) => {
    division(addResult, (divisionResult) => {
      console.log('innermost', divisionResult);
    });
  });
})

Related