Callback functions

maktha chethanmaktha chethan
2 min read

Callbacks are functions that are passed as arguments to another function,to be executed only after task in function has been completed.

Example:

function order(item,callback){ 
     console.log(preparation of ${item} is complete);
     callback();
}
function notify(name){
     console.log(${name},your order is ready);
}
order("coffee",()=>notify("john")); 
//here callback function notify executes only after preparation of item is complete.

Asynchronous Callbacks:

Callbacks are most useful when dealing with asynchronous operations, such as reading files, making network requests, or waiting for timers.

example

function setAlarm(time, callback) {
    console.log(`Alarm set for ${time} AM.`);
    setTimeout(() => {
        callback();  // The callback (wakeUp) is called after 7 seconds
    }, time*1000); 
}
function wakeUp() {
    console.log("Time to wake up!");
}
// Setting the alarm after 7 seconds
setAlarm(7, wakeUp);

Error-first convention:

It is a common pattern in js, where the first argument of the callback function is error and the second argument is used for the result of the operation. This convention allows for easy error handling in asynchronous operations.

Callback hell:

It happens when callbacks are nested within callbacks, making the code difficult to read, maintain and debug.It is also known as pyramid of doom.

example:

getUser(1, (err, user) => {
    if (err) {
        console.error(err);
    } else {
        getPosts(user, (err, posts) => {
            if (err) {
                console.error(err);
            } else {
                getComments(posts[0], (err, comments) => {
                    if (err) {
                        console.error(err);
                    } else {
                        console.log("Comments:", comments);
                    }
                });
            }
        });
    }
});

Inversion of control:

When using callbacks,it seems like we are losing control of our code, because we using callbacks to dictate behavior.

  • In summary, callbacks are useful, but when managing a lot of asynchronous operations, we usually prefers Promises or async/await syntax to avoid "callback hell" and write more maintainable code.
0
Subscribe to my newsletter

Read articles from maktha chethan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

maktha chethan
maktha chethan