Async Collection Methods
Let’s try to solve this problem without bringing in any utility functions. The simplest approach that I can think of is to run each readFile from the callback of the previous one, while keeping track of the number of callbacks that have fired so far in order to eventually show the output. Here’s my implementation:
Asyncjs/seriesByHand.js | |
| var fs = require('fs'); |
| process.chdir('recipes'); // change the working directory |
| var concatenation = ''; |
| |
| fs.readdir('.', function(err, filenames) { |
| if (err) throw err; |
| |
| function readFileAt(i) { |
| var filename = filenames[i]; |
| fs.stat(filename, function(err, stats) { |
| if (err) throw err; |
| if (! stats.isFile()) return readFileAt(i + 1); ... |
Get Async JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.