No Thanks to Callback Hell

Any method that does not return instantaneously should be asynchronous. The traditional approach to designing asynchronous functions relied on callbacks. Let’s take a look at a small example and discuss the issues with this approach.

​ ​const​ fs = require(​'fs'​);
​ 
​ ​const​ displayFileContent = ​function​(pathToFile) {
​  ​const​ handleFile = ​function​(err, contents) {
​  ​if​(err) {
​  console.log(err.message);
​  } ​else​ {
​  console.log(contents.toString());
​  }
​  };
​ 
​  ​try​ {
​  fs.readFile(pathToFile, handleFile);
​  } ​catch​(ex) {
​  console.log(ex.message);
​  }
​ };

We first bring in the fs library that ...

Get Rediscovering 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.