Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
loging the response.json() inside the then() method before returning the response.json() promise

I'm learning web development so maybe the question is already asked but I haven't found it. I tried to log response.json() inside the .then method before returning the response.json() promise to the second .then handler function. The problem I'm facing is that although the response.json()'s result is being logged, the code in the next .then method is not being executed. Here's my code:

const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');

console.log(fetchPromise)
    
fetchPromise
.then( response => {
  console.log(response.json())
  return response.json();
})
.then( json => {
  console.log(json[0].name);
});

The code is supposed to log response.json()'s result and then end with logging "baked beans" in the second .then handler, but it just logs the promise object and nothing happens afterwards. This code, however, seems to work:

const fetchPromise = fetch('https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json');
console.log(fetchPromise)
    
fetchPromise
.then( response => {
  var resp=response.json() // save the value first
  console.log(resp)
  return resp
})
.then( json => {
  console.log(json[0].name);
});

So why does storing the result in a variable work, but directly calling it doesn't?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the console, you'll see this error:

Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream already read

That's because you cannot execute response.json() twice. Simply move the console.log down to the last .then and log json instead of res.json:

fetchPromise
.then( response => {
  console.log(response.json()) // remove this line
  return response.json()
})
.then( json => {
  console.log(json); // add this line
  console.log(json[0].name);
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda