Search code examples
javascriptasynchronousecmascript-6async-awaites6-promise

Promise.All conditionally await promises


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?


Solution

  • 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.