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.