JPGygax68
7/3/2013 - 9:30 AM

Simple pattern to detect when nested asynchronous operations are fully done. Caveats: no error handling - use for simple scripts only!

Simple pattern to detect when nested asynchronous operations are fully done. Caveats: no error handling - use for simple scripts only!

"use strict";

var pending_asops = 0;
var global_data;

startingAsop();
asyncFunction('param1', 'param2', function(err, data) { global_data = data; } );

function allDone() {
  // Use the complete data!
  console.log('All done!');
  console.log(global_data);
  asopDone();
}

//----------

function asyncFunction(param1, param2, onDone) {
  console.log('asyncFunction()', param1, param2)
  
  // Initiate asynchronous data access, calling dataObtained() when finished ...
  // getData(param1, param2, mainDataObtained);
  /* SIMULATING (REMOVE THIS LINE!) */ dataAccessDone(null, { main: 'abcdefg', details: [] } );
  
  function dataAccessDone(err, data) {
  
    // Signal to the caller that we have the main data (but NOT the detail data, not yet!)
    onDone(err, data); 
    
    // Initiate asynchronous access to detail data
    startingAsop(); // signals start of "detail" data access
    // getDetailData(1000, detailDataObtained);
    /* SIMULATING (REMOVE THIS LINE!) */ detailDataObtained(null, '0123456789');
    
    asopDone(); // signals conclusion of "main" data access
    
    function detailDataObtained(err, detail_data) {
      data.details.push( detail_data ); // ONLY AN EXAMPLE
      asopDone();
    }
  }
}

//----------

function startingAsop() { pending_asops ++; }
function asopDone()     { if (--pending_asops === 0) allDone(); }