2

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

5
  • Try putting console.log(data1) within the foreach after data1.push(object); and please paste what is the value printed in the console Commented May 23, 2020 at 8:02
  • you should include what data is btw Commented May 23, 2020 at 8:08
  • [{…}] 0: {_id: "5ec8ae3e1e6fdd2c24c32e75", productname: "dfdfdfdfdf version3", category: "Mens", price: 49, discount: 55, …} 1: {_id: "5ec8ae3e1e6fdd2c24c32e75", productname: "dfdfdfdfdf version3", category: "Mens", price: 49, discount: 55, …} 2: {_id: "5ec8ae3e1e6fdd2c24c32e75", productname: "dfdfdfdfdf version3", category: "Mens", price: 49, discount: 55, …} length: 3 proto: Array(0) Commented May 23, 2020 at 8:09
  • added an for await version if you're comfortable using more modern syntax Commented May 23, 2020 at 8:22
  • i tried for await but now im getting an error "item not defined" Commented May 23, 2020 at 8:38

4 Answers 4

3

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

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}
]

Comments

0

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.

Comments

-1

You should await .forEach(), but it doesn't exist an async version of .forEach.

Check this: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.