Promises

Learn how to use Promises in JavaScript to simplify asynchronous code and avoid callback hell.

Callback hell

The asynchronous nature of JavaScript does take some time to get used to. Any time we need to wait for a resource or wait for user input, we need to implement a callback mechanism to handle this correctly.

Unfortunately, as a code base grows, we find that we need to rely on callbacks more and more. This can easily lead to what is known as callback hell, where we have so many callbacks that are nested in other callbacks that the code becomes increasingly difficult to read and maintain.

Example of callback hell

As an example of this, let’s consider some code that must read three files one after the other and print their contents.

Press + to interact
// Import the 'fs' module and use it to read the contents of different text files.
import * as fs from "fs";
// The 'readFile' function is used to read the contents of the first text file, 'test1.txt'.
fs.readFile("./test1.txt", (err, data) => {
if (err) {
console.log(`an error occurred : ${err}`);
} else {
console.log(`test1.txt contents : ${data}`);
// The 'readFile' function is used to read the contents of the second text file, 'test1.txt'.
fs.readFile("./test2.txt", (err, data) => {
if (err) {
console.log(`an error occurred : ${err}`);
} else {
console.log(`test2.txt contents : ${data}`);
// The 'readFile' function is used to read the contents of the third text file, 'test1.txt'.
fs.readFile("./test3.txt", (err, data) => {
if (err) {
console.log(`an error occurred : ${err}`);
} else {
console.log(`test3.txt contents
: ${data}`);
}
});
}
});
}
});
  • We are importing the Node filesystem library named fs on line 2, using our standard module syntax.

  • We then call the readFile function of the fs library in order to read a file from disk on line 4. This readFile function takes two parameters:

    • The first parameter is the filename itself, which is "./test1.txt".

    • The ...