Home > Enterprise >  Call async await in parallel with an indeterminate amount of calls?
Call async await in parallel with an indeterminate amount of calls?

Time:05-22

So I have an indeterminate amount of calls I wish to run in parallel in any example I have seen the amount of promises are known from the start.

await Promise.allSettled([someCall(), anotherCall()]);

My issue is I don't know how many promises will be required in the code below I might have 4 delays or 50 delays of various lengths however it does not seem to await for me any thoughts.

let qq = bulk([1,2,3,4,5]);
console.log('last');

async function bulk(array){
  const promiseArray = [];
  for (const delay of array) {
    promiseArray.push(bulkQuery(delay));
  }
  const valueArray = await Promise.allSettled(promiseArray);
}

async function bulkQuery(delay){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(delay);
      resolve('foo');
    }, delay*1000);
  });
}

CodePudding user response:

Your code actually works, but only in the context of bulk. Since bulk itself is async, it's actually a promise behind the scenes, so you have to treat it like a promise!

When you do:

let qq = bulk([1,2,3,4,5]);
console.log('last');

You are not waiting for qq promise to resolve and you log last right away. What you should do is -

let qq = bulk([1,2,3,4,5]);
qq.then(() => console.log('last'));

CodePudding user response:

make it like this instead, there are problems in a way you write your function.

async function myFunction() {
  let qq = await bulk([1,2,3,4,5]);
  console.log('last');
  
  async function bulk(array){
    const promiseArray = [];
    for (const delay of array) {
      promiseArray.push(bulkQuery(delay));
    }
    const valueArray = await Promise.allSettled(promiseArray);
  }
  
  async function bulkQuery(delay){
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log(delay);
        resolve('foo');
      }, delay*1000);
    });
  }
}

myFunction();

by design your method bulk is also a 'thenable' function(returns promise). Which means execution inside the bulk will be as per async and await but any async method also returns a promise which means either you need to write a then or make an await by making this entire function as async await(as I have done in the code snippet)

  • Related