Skip to Main Content
Async JavaScript
book

Async JavaScript

by Trevor Burnham
November 2012
Intermediate to advanced content levelIntermediate to advanced
106 pages
2h 20m
English
Pragmatic Bookshelf
Content preview from Async JavaScript

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Asynchronous JavaScript

Modern Asynchronous JavaScript

Faraz K. Kelhini
Learn TypeScript 3 by Building Web Applications

Learn TypeScript 3 by Building Web Applications

Sebastien Dubois, Alexis Georges

Publisher Resources

ISBN: 9781941222782Errata