cant access object attributes from js array

Viewed 147

i have this simple code to get some objects from api and add it to an array

 const res = await fetch("http://localhost:5000/cart/carts/"+this.state.user);
  const data = await res.json();
 let data1 = [];
    data.forEach(async item => {
        const res1 = await fetch("http://localhost:5000/storemanger/products/"+item.product);
          const object = await res1.json();
          data1.push(object);
      });
console.log(data1)

output of console log

output chrome console

but if try to access first element like

console.log(data1[0])

output is "undefined "

i want to access the productname of objects inside the array

4 Answers

Try this,

let data1 = [];

const promiseArray = data.map(item => fetch("http://localhost:5000/storemanger/products/"+item.product))

Promise.all(promiseArray)
.then(result => Promise.all(result.map(v => v.json()))
.then((values) => {
  data1 = values
});

Your problem is that you don't wait for the fetch calls to be completed. Since your forEach runs an async function, the browser will run them asynchronously (this means they will be scheduled to run at some other time). Your code therefore becomes equivalent to:

let data1 = []
console.log(data1)

Each of these fetch calls return a Promise. If you want to ensure that data1 has the required values, you need to wait for the Promises to be fulfilled.

As an example, you can do the following:

const promises = data1.map(url => fetch(url));
Promise.all(promises).then(values => console.log(values));

Note that the callback will be called when all requests complete. Also note that this code does not take care of handling failed fetches.

If you prefer async/await syntax alternative:

You can use for await ... of syntax.

Using json placeholder as an example

const response = []

const data = [1,2,3]

for await (item of data) {
  const res = await fetch("https://jsonplaceholder.typicode.com/todos/" + item);
  const obj = await res.json()
  response.push(obj)
}

console.log(response) //

response at the end yields

[
  {userId: 1, id: 1, title: "delectus aut autem", completed: false},
  {userId: 1, id: 2, title: "quis ut nam facilis et officia qui", completed: false},
  {userId: 1, id: 3, title: "fugiat veniam minus", completed: false}
]
Related