Skip to content
Advertisement

what’s the difference between using then in argument and not

what’s the difference between these two promises one is used in argument other outisde , which one is preferred

fetch(API_URL + "films")
  .then(response => response.json())
  .then(films => {
    output.innerText = getFilmTitles(films);
  })
  .catch(error => output.innerText = ":(")

fetch(API_URL + "films")
  .then(response => 
    response.json()
      .then(films => {
        output.innerText = getFilmTitles(films);
      }))
  .catch(error => output.innerText = ":(")

Advertisement

Answer

This is probably opinion based. I think the first one is preferred because you won’t end up with nested promises and should be easier to read.

To make it more obvious:

fetch(API_URL + 'films')
  .then(response => response.json())
  .then(films => {
    output.innerText = getFilmTitles(films);
  })
  .catch(error => output.innerText = ':(');

vs

fetch(API_URL + 'films')
  .then(response => response.json()
    .then(films => {
      output.innerText = getFilmTitles(films);
    })
    .catch(error => output.innerText = ':(')
  );

The number of indentation of the second way would grow while the number of indentations in the first approach is fixed.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement