The Async Ordering Problem

Suppose we want to read all of the files in the recipes directory, in alphabetical order, and then concatenate their contents into a single string and display it. We could do this quite easily using synchronous methods.

Asyncjs/synchronous.js
​ 
​var​ fs = require(​'fs'​);
​ 
process.chdir(​'recipes'​); ​// change the working directory​
​ 
​ 
​var​ concatenation = ​''​;
​ 
​ 
fs.readdirSync(​'.'​)
​ 
.filter(​function​(filename) {
​ 
​// ignore directories​
​ 
​return​ fs.statSync(filename).isFile();
​ 
})
​ 
.forEach(​function​(filename) {
​ 
​// add contents to our output​
​ 
concatenation += fs.readFileSync(filename, ​'utf8'​);
​ 
});
​ ...

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.