0

I want to iteratate through my result array. But even when I am pushing only numbers to the array the length function is not working on this. In the webbrowser I clearly see that the array is created. But when I want to use the lengh-function it only shows 0.

Picture of the programm result

let array = [];

fetch('./api/getFromDatabase', {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
  }).then(response => response.json())
  .then(data => {
    data.forEach(tocken => {
      array.push(3);
    })
  })
  .catch(err => alert(err))

console.log(array);
console.log(array.length); //not working

let array1 = [3, 4, 2];
console.log(array1);
console.log(array1.length); //working
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
eliasRagel
  • 17
  • 5
  • 1
    use async/await for `fetch`. Thats should fix your issues – Muthukumar Dec 29 '22 at 05:24
  • You're performing your logs before the `.then()` callback has ran. Put your logs inside of the `.then()` callback instead. For expanded objects (and arrays), the browser console isn't showing you the value of the object at the time of logging, but rather it is showing you the object at the time of expanding it in the console (you'll see that if you hover over the little "i" in the console). The non-expanded version of the array is what it holds at the time of the log – Nick Parsons Dec 29 '22 at 05:27

0 Answers0