How to avoid callback hell in Node.js?

Technology CommunityCategory: Node.jsHow to avoid callback hell in Node.js?
VietMX Staff asked 3 years ago

Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than expected. Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the callback associated. Sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be.

There are four solutions which can address the callback hell problem:

  • Make your program modular – It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.
  • Use async/await mechanism – Async /await is another alternative for consuming promises, and it was implemented in ES8, or ES2017. Async/await is a new way of writing promises that are based on asynchronous code but make asynchronous code look and behave more like synchronous code.
  • Use promises mechanism – Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises requires the use of .then() function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.
  • Use generators – Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions uses a special syntax function* (). They can also suspend and resume asynchronous operations using constructs such as promises or thunks and turn a synchronous code into asynchronous.
    function* HelloGen() {
      yield 100;
      yield 400;
    }
    
    var gen = HelloGen();
    
    console.log(gen.next()); // {value: 100, done: false}
    console.log(gen.next()); // {value: 400, done: false}
    console.log(gen.next()); // {value: undefined, done: true}