async/await makes it easier to work with asynchronous code in javascript. Understand how it works and why we should use it is important to get the best out of it.

Photo by Joshua Aragon on Unsplash

To truly understand async/await, we need to go through the history of dealing with asynchronous code in javascript:

Callbacks

Let’s say we want to read a file, format its content, save it in another file and then print a success message.

This is how it will look using callbacks:

const fs = require('fs'); fs.readFile('./doc.txt', (err, content) => {

const formattedContent = content.toString().toUpperCase();

fs.writeFile('./doc2.txt', formattedContent, (err) => {

if (!err) {

console.log('success!!')

}

});

});

readFile here accepts the path of the file that needs to be read and the callback function that it will execute after reading the file.

The callback function will then format the content and write the result into another file. writeFile here accepts the new file path, content and the callback function that will execute after the file is written to the disk.

The problem with callbacks is more apparent in the following:

getSomeData(() => {

getMoreData(() => {

doSomethingWithTheData(() => {

saveUpdatedData(() => {

refreshCache(() => {

logOutput()

})

})

})

})

});

Whenever we want to do more than 2–3 asynchronous operations one after the other, we will fall into callback hell. This can result in confusing code.