O'Reilly logo

Async JavaScript by Trevor Burnham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required