Last active
December 6, 2016 15:05
-
-
Save ptdecker/3ece65c029b0c4358027 to your computer and use it in GitHub Desktop.
Node.js Serial Execution of an Async Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Control Flow 1 - Repetitive Serial Execution of an Asynchronous Function | |
* | |
* Based on: | |
* - http://book.mixu.net/node/ch7.html | |
* - https://github.com/mixu | |
* | |
* Revised to use "typeof(first_item) != 'undefined'" based upon comments from 'Israel' | |
* | |
* Characteristics: | |
* - Flow control construct 'series' is recursive | |
* - Runs a number of operations sequentially | |
* - Only starts one async operation at a time (no concurrency) | |
* - Ensures that the async function complete in order | |
* | |
* Variations: | |
* - The way in which the result is collected (manual or via a “stashing” callback) | |
* - How error handling is done (manually in each subfunction, or via a dedicated, additional function) | |
* - Since execution is sequential, there is no need for a “final” callback | |
* | |
* Tags: sequential, no-concurrency, no-concurrency-control | |
*/ | |
/* | |
* A Simulated Asynchronous Function | |
*/ | |
function async(arg, callback) { | |
var delay = Math.floor(1000 * Math.random()); | |
console.log('Do something with "' + arg + '", and return ' + delay + 'ms later'); | |
setTimeout(function() { | |
result = arg; // Keep results same as argument so impact of async can be viewed | |
callback(result); | |
}, delay); | |
} | |
/* | |
* A Simulated Completion Function | |
*/ | |
function final(results) { | |
console.log('Done', results); | |
console.log(process.hrtime(start)[0] + "." + (process.hrtime(start)[1] / 1000000).toFixed(0) + " sec(s) total time"); | |
} | |
/* | |
* Recursive 'Series' Flow Control Construct | |
*/ | |
function series(remaining_items, results) { | |
var first_item = remaining_items.shift(); | |
if (typeof(first_item) != "undefined") { | |
async(first_item, function(result) { | |
results.push(result); | |
console.log('Results so far: ', results); | |
return series(remaining_items, results); | |
}); | |
} else { | |
return final(results); | |
} | |
} | |
/* | |
* Main | |
*/ | |
var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Work array | |
var results = []; // Results array | |
var start = process.hrtime(); // Start a timer | |
series(items, results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment