0

I have the following code

export const backend = {
  listAll: () => {
    let collection = [];

    axios
      .get("http://localhost:5000", {headers: {"Accept": "application/json"}})
      .then(response => response.data.forEach(entry => collection.push(entry)))
      .catch(error => console.log(error));

    console.log("result: ", collection, collection.length;
    return collection;
  }
}

The console output is:

result:  Array [] 0

(expanded array)
[]
​
0: Object { identity: "1580db04-4329-48c5-8d0f-e6b47be5cb90", name: "aaa" }
​1: Object { identity: "2227b700-1cbd-4635-ad9f-de18a552a686", name: "bbb" }
​2: Object { identity: "c47cedcc-be16-4806-9f8d-865c9bbec8f7", name: "ccc" }
​3: Object { identity: "e07953a9-dbfa-4ff1-ad8b-4797879ba7f3", name: "ddd" }
​4: Object { identity: "e4b25633-3bea-4ab0-aa07-7e7a03df3a52", name: "eee" }
​5: Object { identity: "f96a54ac-ebb3-494b-a5e2-2407a936e465", name: "fff" }
​
length: 6
​
<prototype>: Array []

So the console output is telling me that collection.length is zero, but the expanded array show me the correct content. The calling code receives an empty array. Why the array is empty?

Bruno Araújo
  • 91
  • 2
  • 9
  • You have a asynchronous function, you need to the log inside of promise (then) .then(response => { response.data.forEach(entry => collection.push(entry)); console.log(collection); } ) – barrilocho Feb 25 '21 at 16:25
  • The main point here is that the calling function is getting an empty array... – Bruno Araújo Feb 25 '21 at 17:10

0 Answers0