0

I have a list of async functions that each have a condtion such that the function should be called if and only if the corresponding condition is met and I want to run all of the functions parallely. Example:

await Promise.all([asyncFunc1(), asyncFunc2(), ...]) 

Each function in the list should be called if and only if the corresponding conditions: cond1, cond2, ... are met. What is the best way of doing this?

  • 2
    The functions will not run in parallel. – Pointy Dec 11 '20 at 13:34
  • It makes no sense to not wait for a function that you're calling. Do you mean you actually don't want to *call* the respective function based on the conditions? – Bergi Dec 11 '20 at 13:42
  • @Bergi Yes. Sorry about that, I'll edit the question –  Dec 11 '20 at 13:53
  • 2
    OK, in that case you found the appropriate solution :-) – Bergi Dec 11 '20 at 13:54
  • @Pointy Mabye I've misunderstood this answer: https://stackoverflow.com/a/35612484/7964141 Is there a way to run all of the asynchronous functions in parallel? –  Dec 11 '20 at 13:58
  • 2
    Launching a bunch of asynchronous operations *may* result in parallel execution *outside* the context of JavaScript, but that's up to whatever service the operations involve. As far as JavaScript itself is concerned, the operations will result in events when they succeed or fail, and those events will be processed one at a time as they occur. – Pointy Dec 11 '20 at 13:59
  • @Pointy That makes a lot of sense. Thanks for the clarification! –  Dec 11 '20 at 14:02

2 Answers2

1

I came up with this very simple solution:

const promiseList = []
if(cond1) promiseList.push(asyncFun1())
if(cond2) promiseList.push(asyncFun2())
...
await Promise.all(promiseList)
0

Put your conditions into an array, and filter the function list with it:

const conditions = [cond1, cond2, cond3, cond4]
const functions = [asyncFunc1, asyncFunc2, () => asyncFunc3(foo), bar.asyncFunc4.bind(bar, baz)]

await Promise.all(
  functions
    .filter((_, i) => conditions[i])
    .map(fn => fn())
)

To pass parameters to your async functions (or preserve their this context), .bind them, or wrap them in other functions.

FZs
  • 16,581
  • 13
  • 41
  • 50