fetching each item inside an array

So I’m pretty sure this have something to do with Promise.all or something like that but I’m not sure how to do it. will appreciate if someone can help me out with this code.

Note: the array I’m trying to map is an array of objects if that matters

const productsArray = this.cartProducts.map(product => 
      fetch(`/api/products/getDetails/${product.clientId}`))
      .then(res => res.json())
      .then(data => {
        console.log(data)
      })

I’m not able to even launch this code but I’m not sure what I should do exactly…

This is my error from visual studio code.

property 'then' does not exist on type 'promise<response>[]'

Answer

fetch() result is promise so you need to use Promise.all()

const promises = await Promise.all(this.cartProducts.map(product => fetch(`/api/products/getDetails/${product.clientId}`))
const productsArray = await Promise.all(promises.map(p => p.json()))

Leave a Reply

Your email address will not be published. Required fields are marked *