call function in object parameter - await fetch to change object element

Viewed 20

I don't understand why it returns each fruit with the same size. It's like it returns only the fruit size of the first fruit / first fetch result. I mean allFruits has always the same size, thats not correct. And make an await in the object element like { name: await getFruitName(f.1)} does not work. Maybe the function should be called in another place?

const food = await fetchFood();
food.entries.map(await fruits)

var allFruits =  {}
async function fruits(f) {
  allFruits=
   {
    name: getFruitName(f.1)
   }

 let fruitSize = await FetchFruitsSize(f.2)
 allFruits.size = fruitSize.data[0].sizes[1]
}

return allFruits

If somebody has an example how to change the object value for each array element with calling a function that is calling a fetch, I would be very greateful

1 Answers

Some issues:

  • allFruits should be an array, and the individual objects that your code creates should become entries in that array, so it becomes an array of objects.

  • The async fruits callback returns a promise that resolves to undefined, because there is no return statement.

  • In map(await fruits) it makes no sense to use await for a function object (which is not a promise). Just drop that await keyword.

  • food.entries.map(fruits) returns an array of promises, but your code does not await those promises. You should feed them to Promise.all and await that combined promise to resolve.

  • f.1 and f.2 are not valid syntax: if 1 and 2 are supposed to be properties of f, then you need square brackets. But it doesn't look like f is an array, so I have just dropped those syntax issues in below proposed code: adapt as needed.

The above points are resolved in this version:

(async function () {
    const food = await fetchFood();
    const allFruits = await Promise.all(food.entries.map(fruits));
    // Do something with the fruits... 
    console.log(allFruits);

    async function fruits(fruit) {
        let fruitSize = await FetchFruitsSize(fruit); // adapt to do f.2
        return {
            name: getFruitName(fruit), // adapt to do f.1
            size: fruitSize.data[0].sizes[1]
        };
    }
})();

There might still be other issues that relate to what the functions return that are called here... including: fetchFood, FetchFruitsSize, and getFruitName.

Related