No Thanks to Callback Hell
Let's discuss which problems we can face while using callbacks in asynchronous programming.
We'll cover the following...
Any method that does not return instantaneously should be asynchronous.
Callbacks in asynchronous programming
Traditionally, designing asynchronous functions relied on callbacks. Let’s take a look at a small example and discuss the issues with this approach.
Press + to interact
'use strict';//START:DEFINEconst 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);}};//END:DEFINE//START:GOODCALLdisplayFileContent('readfile.js');//END:GOODCALL//START:INVALID_FILEdisplayFileContent('does-not-exits');//END:INVALID_FILE//START:NOFILEdisplayFileContent();//END:NOFILE
Explanation
First, we bring in the fs
library, which provides both synchronous and asynchronous functions to read files.
📍 The
require()
method is used to load JavaScript modules. ...