DEV Community

Discussion on: What are Promises in Javascript ? (Help)

Collapse
 
lexlohr profile image
Alex Lohr

JavaScript usually runs one command after another. Sometimes, commands take longer, i.e. HTTP Requests; running them that way will block the whole page. Instead, JavaScript runs these things in a way that calls a function (usually called callback) after the command has finished. However, just calling a function that you receive as an argument leads directly into callback hell:

request1(config, function callback1(data) {
  request(data.secondUrl, function callback2(data) {
    request(data.thirdConfig, function callback3(data) {
      // and so on and so forth
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

As you can clearly see, this code gets ugly fast. Helpfully, JavaScript now has a class called Promise which helps to make this more manageable:

  fetch(config)
    .then((data) => fetch(data.secondUrl))
    .then((data) => fetch(data.thirdConfig))
  // and so on and so forth
Enter fullscreen mode Exit fullscreen mode

This way, the code becomes much more readable and still does not block the page.

Collapse
 
sojinsamuel profile image
Sojin Samuel

Thanks for colaborating, your answers would help me a lot for my reference