0

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?

2
  • 6
    Sure, unless you can make all the calls to getRes at the same time, in which case you Promise.all them and then sum them up. Commented Nov 19, 2021 at 20:56
  • 2
    const sum = await Promise.all(ids.map(id =>getRes(id))).then(nums=>nums.reduce((a,b)=>a+b)); Commented Nov 19, 2021 at 21:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.