The callback hell

Well, in Javascript programming, it is very usual to do a callback. But once it becomes chaining multiple and nesting one asynchronous data into another multiple times, we fall into what we call callback hell. Let's take this example below.

fetch('https://api.example.com/data1')
  .then(response => response.json())
  .then(data1 => {
    return fetch(`https://api.example.com/data2/${data1.id}`)
      .then(response => response.json())
      .then(data2 => {
        return fetch(`https://api.example.com/data3/${data1.id}/${data2.value}`)
          .then(response => response.json())
          .then(data3 => {
            // Process data3
          })
      })
  })
  .catch(error => {
    console.error('Error:', error);
  });

this above example shows the callback hell example. the second then method is nested with 2 more then method nested in it .which also have 2 more nested in them too, believe me it is a bad code type

that is how it is to fall though we can’t escape callback in JS but it can be avoided in different ways by ;

  1. preventing unnecessary nesting of the “ .then( ) “method

  2. by catching the errors i.e handling them, by using the “.catch( )” method. (more on this in my next post soon😊)

  3. Or even creating functions(helping functions) for them to prevent repetition of code just like DRY in coding general.

    nice to meet you guys. still muzzammil by name.