jason135
jason135

Reputation: 189

async loops in javascript

I am trying to sum up the results which got from a series of async call

let sum = 0;
for(const id  of ids) {
  const res = await getRes(id);
  sum += res;
}

Is this a valid way to do it? Any better solution?

Upvotes: 0

Views: 54

Answers (1)

Enrico Massone
Enrico Massone

Reputation: 7348

The code that you have written seems to be correct.

In order to validate it you can write some unit tests, I can't say how difficult it is because I don't know what getRes is doing and what external dependencies (if any) you have to mock. Generally speaking you should take the habit of unit testing your code: one of the benefits it brings to the table is offering you a way to validate your implementation.

You can also consider the idea of getting the results in parallel, this can actually speed things up. Again I don't know what getResis doing, but I suppose it performs some sort of IO (e.g.: a database query). Given the single thread nature of Javascript, when you have a bunch of independent asynchronous operations you can always try to perform them in parallel and to collect their results, so that you can aggregate them later. Please notice the bold on the word independent: in order to perform a bunch of operations in parallel they need to be independent (if they are not, the correctness of your code will be invalidated).

Since you are performing a sum of number, it is safe to compute the addends in parallel.

This is the simplest possible parallel solution:

async function sum(ids) {
    const getResTasks = ids.map(id => getRes(id));
    const addends = await Promise.all(getResTasks);
    return addends.reduce((memo, item) => memo + item, 0);
}

Pay attention: this is a naive implementation. I don't know how many items the ids array can contain. If this number can possibly be huge (thousand of items or more) a code like the previous one could create an heavy load on the external dependency used to get the sum addends, so some precautions to limit the degree of parallelism should be taken.

Upvotes: 2

Related Questions