Executing async functions in parllel

·

1 min read

Problem Statement : Implement a function that takes a list of async functions as input and a callback function and executes the input tasks in parallel i.e all at once and invokes the callback after every task is finished

Example:

Input: executeParallel( [asyncTask(3), asyncTask(1), asyncTask(2)], (result) => { console.log(result);});

Output: // output in the order of execution [2, 1, 3]

function asyncParllel(tasks , callback){
  // so results is an array
  const results = []

  //  tracking tasks which are excuted
  let tasksCompleted = 0;

  // run tasks
  tasks.forEach(asyncTask=>{
    // invoke async task which can be promise so chain a then
    asyncTask(value=>{
      //  store the output in results
      results.push(value)

      //  increment tracker
      tasksCompleted++;


//  if all tasks are completed , invoke callback
      if(tasksCompleted >= tasks.length){
        callback(results)
      }

    })
  })

}

I have used for each loop on each task and executed them , so i need tracker because of this tracker i can know how many tasks are completed , so we do this because invoking a callback at the end of loop won't work because i don't know when they may finish

That's it for now

Have a great day