Where the Wild Things Are →← Why is the african ant eater always tired?

Here is a simple function I wrote to collect the results of multiple asynchronous function calls and pass them as a list to a single function.

function parallelExecuter(executer, operationCount){
  var parameters = [];
  var n = 0;
  var ctr = 0;
  function makeParallel(operation){
    var id = n;
    n++;
    function cookie(){
      parameters[id] = arguments;
      ctr++;
      if(ctr == operationCount){
        executer(parameters);
      }
    }
    operation(cookie);
  }
  return makeParallel;
}

Using it is quite simple. Define two functions getOne and getTwo, which will act as asynchronous functions. Each accepts one paramerter which is called with an integer value as it's parameter. And a function, sum, that totals the the numbers in a list and displays an alert box with that value.

function getOne(callback){
  callback(1);
}
function getTwo(callback){
  callback(2);
}

function sum(l){
  var total=0;
  for(var i=0; i < l.length; i++) {
    total+=l[i];
  }
  alert(total);
}

Call parallelExecuter with the final function to call and the number of asynchronous operations, here sum and 2 respectively. This returns a function which is used to queue the asynchronous calls, getOne and getTwo. Note that the number of asyncronous operations should be the same as was specified for creating the function or the code will break.

pe = parallelExecuter(sum,2);
pe(getOne);
pe(getTwo);

This will display an alert box containing the value 3.

A better design would be to aggregate all the pieces into a single request, but this might not be possible at times.