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

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'​);
 
});
 
 
console.log(concatenation);

(Be aware that the forEach iterator isn’t available in older JavaScript ...

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