codeofnode
codeofnode

Reputation: 18609

How to call multiple dynamic await in parallel in javascript

Taking this this example

The parallel example is

async function add1(x) {
  var a = resolveAfter2Seconds(20); // return promise
  var b = resolveAfter2Seconds(30); // return promise
  return x + await a + await b;
}

What if i have a, b, c, d, and so on that's all dynamic say array

something like this

async function add1(x) {
  var arrayOfPromises = [resolveAfter2Seconds(20), resolveAfter2Seconds(30)];
  return x + arrayOrPromises; // i am expecting same result, but it differes.
}

So what is the current syntax for array over await.

Edit : The main issue is, what if i have 10, 100, or 100000 promises? How would you write a0 + a1 +... a10000 ?

Upvotes: 0

Views: 406

Answers (2)

Erazihel
Erazihel

Reputation: 7605

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function add1(x) {
  var arrayOfPromises = [resolveAfter2Seconds(20), resolveAfter2Seconds(30), resolveAfter2Seconds(40)];
  return x + (await Promise.all(arrayOfPromises)).reduce((a, b) => a + b, 0);
}

async function add2(x) {
  var a = resolveAfter2Seconds(20); // return promise
  var b = resolveAfter2Seconds(30); // return promise
  return x + await a + await b;
}

add1(10).then(v => {
  console.log('add1', v);  // prints 100 after 2 seconds.
});

add2(10).then(v => {
  console.log('add2', v);  // prints 60 after 2 seconds.
});

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138235

Extending Erazihels answer to return the right value:

async function add1(x) {
  var arrayOfPromises = [resolveAfter2Seconds(20), resolveAfter2Seconds(30)];
  return x + (await Promise.all(arrayOrPromises)).reduce((a,b)=>a+b,0); 
}

or:

async function add1(x) {
  [a,b] = await Promise.all([resolveAfter2Seconds(20), resolveAfter2Seconds(30)]);
  return x + a +b; 
}

Upvotes: 0

Related Questions