0

I got data from API and tried to push it in an array, but when I print it, it's empty. The data is JSON.


fetch("url")
        .then((response) => response.json())
        .then((data) => sohawnID.push(data.id))
        console.log(sohawnID)

//output: []```

Nyaco
  • 1

2 Answers2

0

this is because synchronous behavior of node js. what you need is to put you api call method inside a Promise function and then call it using async await. By this way program 1st wait for api response and then push data to your array

Ali Faiz
  • 212
  • 2
  • 9
0

The reason it prints empty is console.log(sohawnID) called before the promise fulfil meaning you are trying to print result before it arrives. You can do this:

fetch("url")
        .then((response) => response.json())
        .then((data) => {
               sohawnID.push(data.id);
               console.log(sohawnID)
})
        
``
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35