0

I'm trying to iterate asynchronously over list of array elements, but with this code:

const calculate = async ({ id, priority, database, product }) => {
    let list_of_products;
    if (priority) {
        list_of_products = await getPriorityList(database, id);
    }
    else {
        const prods = product.split(',');
        await prods.forEach((prod) => {
            list_of_products = getList(database, prod);
            console.log({ list_of_products });
        });
    }
};

I get the following console.log():

{ list_of_products : Promise { <pending> } }

And of course, an error gets thrown eventually.

What is the best practice to handle async calls when iterating? The getList() method is async as well.

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • You don't need to use async loop. You can just use Promise.all() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – digitalniweb Aug 26 '22 at 17:25
  • 1
    There are many answer [here](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – vee Aug 26 '22 at 17:26
  • `.forEach()` should be stricken from any use with promises as it is not promise-aware. Use a regular `for` loop instead and then you can `await` the promise that `getList()` returns. – jfriend00 Aug 26 '22 at 17:36
  • 2
    Note that `await prods.forEach(...)` is pointless because `.forEach()` has no return value so you're doing `await undefined` which does nothing useful. `await` is ONLY useful when you are awaiting a promise. – jfriend00 Aug 26 '22 at 18:01

1 Answers1

2

do not use async await in forEach loops. await prods.forEach((prod). instead of forEach loop you can use for...of loop. checkout this: Using async/await with a forEach loop

you need to add await keyword in front of your getList(database, prod). otherwise, that async function will return a promise.

I refactored your code.

const calculate = async ({ id, priority, database, product }) => {
    let list_of_products;
    if (priority) {
        list_of_products = await getPriorityList(database, id);
    }
    else {
        const prods = product.split(',');
        for(let prod of prods) {
            list_of_products = await getList(database, prod);
            console.log({ list_of_products });
        }
    }
};

Vinod Liyanage
  • 945
  • 4
  • 13