node.js force async processes to run in series
Node.js is asynchronous I/O that other processes can start and doesn’t have to wait for some long running input/output processes such read and write from files or databases. For example
queryDatabase(); //assume this will take some time, few seconds console.log('This print statement will run before the previous database query function');
For whatever reason if you want to force the long running process to run one after another in series. Here is an example for it
// A list of items need to be processed in series var items = [ 1, 2, 3, 4, 5], startIndex = 0, endIndex = items.length, asyncResults = [], seriesResults = []; // An long time async process, multiple the arg by 2 and pass it to the callback // after 2 seconds has passed // This could be I/O process such as read/write from file or database function longTimeProcess(arg, callback) { setTimeout(function() { callback(arg * 2); }, 5000); } // This is called when all items are processed. function done() { console.log('series results: ', seriesResults); } //recursive call to force each process to run after the previous one is finished. function runAsyncProcessesInSeries(itemIndex) { if( itemIndex < items.length ) { longTimeProcess( items[itemIndex], function(result) { console.log(result); seriesResults.push(result); return runAsyncProcessesInSeries( ++itemIndex ); }); } else { return done(); } } runAsyncProcessesInSeries(startIndex);
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts