Javascript callbacks
adarsh04
Posted on December 14, 2023
This post intends to figure out how to use Javascript callbacks by understanding how they are used in various Javascript libraries.
Let’s start with the simple setTimeout function. If we consider the code below
const startTimer = (printAction) => {
setTimeout(printAction, 3);
};
const printAction = () => {
console.log('print Action');
}
startTimer(printAction);
We are passing another function (printAction) into setTimeout. setTimeout will then call this function once the timer has finished. The printAction function that is called is a callback.
Since the term callback is used, let’s consider this an analogy to a phone call. We make a phone call to setTimeout and inform it of the callback details, i.e. printAction. setTimeout hangs up the phone, waits till the timer is done and then calls us back with printAction.
Let’s consider another use of callbacks in the example below with the readFile function in the node.js file system to realise a significant advantage of callbacks.
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
The readFile function takes in the file it needs to read and a callback. The callback is an arrow function with err and data as params. Once readFile is done, it calls the arrow function (callback). We then throw an error if err is present or log the data.
The advantage is that the file is read asynchronously, which is essential in the Javascript world. The main program can continue to execute and respond to other events, whilst the readFile will execute asynchronously and inform us about the results via a callback.
Feel free to suggest anything in the comments section to improve someone’s understanding of callbacks.
References:
Posted on December 14, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.