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
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
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}
]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments