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

123
Visualizações
Fetch-then returns undefined - Probably issue with async nature of fetch

I am relatively new to JavaScript/React. Working on a simple React App, I am stuck with a real problem I cannot figure it out.

This is the code I am talking about:

const Inventory = () => {
   
    let product = [];
 
    let response = fetch("http://localhost:3000/inventory.json")
    .then( response => response.json() )
    .then( data => data.map( item => {

        product.push(item.name);
    
        }))
    .then (console.log(product[0]))

        
    setTimeout( x => console.log(product[0]), 1000)
        

Inventory.json is a simple file, which I will post here for the sake of completeness:

[   
    {
        "name": "Cookies1",
        "details": "Cookies1D",
        "lastFilled": "5. Jan. 2022",
        "lastReq": "2. Jan. 2022",
        "Status": "full"
    },
       
    {
        "name": "Cookies2",
        "details": "Cookies2D",
        "lastFilled": "5. Jan. 2022",
        "lastReq": "2. Jan. 2022",
        "Status": "full"
    }

]

Now, I expected the code to work as follows:

  1. Fetch will get the Data (which works!)
  2. After that the JSON is extracted from the data (first THEN)
  3. After that the JSON is extracted to an array via map (second THEN)
  4. After that the first array-element is console-logged (third THEN)

However, what I get from the console from my third .then is undefined.

To test whether this issue has something to do with the async nature of fetch I added a line that waits 1 second before it console-logs the first array element ( setTimeout(... ), which works absolutely as expected and console.logs "Cookies1".

But how can that be? My understanding is, that .then is executed after the preceeding commands (i.e. after the preceeding promise has been resolved). That means that .then (console.log(product[0])) should give me the same (defined) result as setTimeout( x => console.log(product[0]), 1000).

Why does my third .then return undefined and how can I solve this? It seems I have got something terribly wrong. Could anyone help me with that puzzle. I really get get exasperated with it.

Kind regards Chris

about 4 years ago · Juan Pablo Isaza
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