...

/

No Thanks to Callback Hell

No Thanks to Callback Hell

Let's discuss which problems we can face while using callbacks in asynchronous programming.

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:DEFINE
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);
}
};
//END:DEFINE
//START:GOODCALL
displayFileContent('readfile.js');
//END:GOODCALL
//START:INVALID_FILE
displayFileContent('does-not-exits');
//END:INVALID_FILE
//START:NOFILE
displayFileContent();
//END:NOFILE

Explanation

First, we bring in the fs library, ...

Access this course and 1400+ top-rated courses and projects.