Callback hell is a situation in Javascript when you face callbacks within callbacks or nested callbacks.

It looks somewhat like this:

firstFunction(args, function() {
   secondFunction(args, function() {
      thirdFunction(args, function() {
      });
   });
});

There are two significant ways to avoid Callback Hell in NodeJS:

1. Using Promises

const makeBurger = () => {
    return getChicken()
    .then(chicken => cookChicken(chicken))
};
makeBurger().then(burger => serve(burger));

See, it is just more easy to read and manage in comparison to the nested callbacks.

2. Use Async/Await

Using Asynchronous functions, we can convert makeBurger into one synchronous code. Also, maybe you can get helpers to getBun and getChicken at the same time, meaning, you can use await with Promise.all. Here's the code:

const makeBurger = async () => {
    const cookedChicken = await cookChicken(chicken);
    return cookedChicken;
};
makeBurger().then(serve);

Suggest An Answer

No suggestions Available!