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.