0

I am trying to retrieve multiple different products through async and await. I manage to do one, but that's because I don't need to iterate through anything, when trying to iterate however, it returns XXX.then is not a function. My knowledge in regards to promises is very little (and therefore practicing it), but the problem is: I can't get a visual on what is returned. My application crashes and that's it. So trying to tweak is difficult.

        let d = [
        "butter",
        "mais",
        "bread"
    ];

    // Search for all products on ascending price with the filter
    let oct = d.map(async function(f) {
        const products = await ah.product().getProductsFromName(f, {
            sort: ProductSortOptions.PriceAsc
        });
        return products;
    });

        oct.then(function(result) {
        const responseTitles = result.products.map((product) => {
            return {
                "title": product.title,
                "brand": product.brand
            };
        });
        res.json({
            prod: responseTitles
        });
    });

I assumed I had to resolve my promise as well, due to the async method in the map, but this doesn't seem to work.

Doing the following, it does work (but I cannot iterate then and I have to hard-code everything):

    const products = await ah.product().getProductsFromName("butter", {
        sort: ProductSortOptions.PriceAsc
    });
        const responseTitles = products.products.map((product) => {
            return {
                "title": product.title,
                "brand": product.brand
            };
  • The return value of the `map` function on an array is an array, not a promise, so it doesn't have a `then` method. If you want to wait for all of the promises in that array to settle, you can use `Promise.all` to do that. See the linked questions answers. – T.J. Crowder Apr 02 '23 at 17:18
  • @T.J.Crowder Correct, but I figured that the values in the array are "not resolved promises". – I try so hard but I cry harder Apr 02 '23 at 18:58

0 Answers0