0

I have problems pushing to an array in a SSR page in the below code.

    let categories = []

    categories = await axios.get(`http:/.../${price_list_name}`).then(res => {
        return res.data
    })

    const child_categories = categories.related.category_childs.hits.hits
    const childs_en_names = []
    if (child_categories.length > 0) {
        for (var doc in child_categories) {
            childs_en_names.push(child_categories[doc]._source.en_name)
        }
    }

    const get_products = async (en_name) => {
        await axios.get(`http://.../${en_name}`).then(res => {
            let data = {
                "en_name": en_name,
                "products": res.data.related.childs_products
            }
            return data
        })
    }

    const products = await Promise.all(childs_en_names.map(en_name => get_products(en_name))) 


    // logging
    // console.log(categories.products, 'props')
    console.log(products, 'products')

cosole.log(products, 'products') returns me undefined or Promise { }. I have searched alot but haven't been successfull to make it work.

any help would be highly appreciated.

m m
  • 17
  • 5
  • `get_products` returns a promise of _undefined_, the data from the request isn't part of the promise it returns. – jonrsharpe May 02 '22 at 11:11
  • so why when I log the data variable it returs me the actual data? and how can I solve it? – m m May 02 '22 at 11:13
  • 1
    Because while the log of that data _inside_ of the `then` callback will show you the data, you can't return the data from that callback like you're trying to do. – Andy May 02 '22 at 11:16

1 Answers1

1

You're not returning anything from get_products. There's no point in using async/await if you're going to use then too. It sort of defeats the point.

const get_products = async (en_name) => {
  const res = await axios.get(`http://.../${en_name}`);
  const data = {
    en_name: en_name,
    products: res.data.related.childs_products
  }
  return data;
}
Andy
  • 61,948
  • 13
  • 68
  • 95