Skip to content

Instantly share code, notes, and snippets.

@JPGygax68
Last active September 18, 2017 19:36
Show Gist options
  • Save JPGygax68/5916646 to your computer and use it in GitHub Desktop.
Save JPGygax68/5916646 to your computer and use it in GitHub Desktop.
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(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment