0

I am still learning Javascript properly and read a few threads on here about asynchronity (1 2). Unfortunately, I have still trouble to find a solution to my problem. I am calling an API in async fashion and would like to create a sum out of the response that I am receiving of multiple async calls.

Let's say I want my code to perform an action if my "sum" has a value of 40. Async call "A" returns 6, async call "B" returns 8, and so on until we finally reach the value of 40. How can I create such a sum, as my calls are all async? Would it require to write each async result to a database and pull the value up in the next async call? Is there a better solution for this?

Thank you for your help.

EDIT: To make things easier to understand I will add some source code:

Webhook.js

router.post('/', (req, res, next) => {
  if (middleware.active)
    middleware.handle(req.body) // <--- this gives me one result
  res.sendStatus(200)
});

Basically, I will receive multiple webhook calls. "middleware.handle" will send an API call to third party application. I want to take the result from that API call and add it to the result of another API call from another webhook request.

As you can see, I don't know when my webhook will be triggered, neither how many times it will be triggered before reaching my desired total of 40.

paaax
  • 144
  • 1
  • 1
  • 8

2 Answers2

0

You can use Promise.all([apiCallOne, apiCallTwo]).then(values => sum(values)) sum being a function that sums an array of numbers

Jacob
  • 524
  • 5
  • 18
0

You can await for both in a do/while loop then do the rest of the logic

async function myFunc() {
   let valA = 0;
   let valB = 0;
   do {
      valA += await fetch('https://api.url.com/a');
      valB += await fetch('https://api.url.com/b');
   } while((valA + valB) < 40 );

You can also do each one in its do/while loop if you want to request value from one only at a time then check condition.

Youssef AbouEgla
  • 1,445
  • 10
  • 21