0% found this document useful (0 votes)
12 views2 pages

Callback Functions QA

Callback functions are functions passed as arguments to other functions and are commonly used for asynchronous operations such as reading files, making API calls, and event handling. Error handling in callback functions is typically done using the 'error-first' pattern, where the first argument of the callback is reserved for an error object. If an error occurs, it is passed to the callback; otherwise, null is passed, allowing for proper error management.

Uploaded by

algo47177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Callback Functions QA

Callback functions are functions passed as arguments to other functions and are commonly used for asynchronous operations such as reading files, making API calls, and event handling. Error handling in callback functions is typically done using the 'error-first' pattern, where the first argument of the callback is reserved for an error object. If an error occurs, it is passed to the callback; otherwise, null is passed, allowing for proper error management.

Uploaded by

algo47177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1. Explain Callback functions and some scenarios where they are used.

A callback function is a function passed into another function as an argument. This function is then

invoked inside the outer function to complete a certain task. Callbacks are often used for

asynchronous operations like:

- Reading files

- Making API calls

- Event handling

Example:

function fetchData(callback) {

setTimeout(() => {

callback('Data loaded');

}, 1000);

fetchData(message => [Link](message));

2. How will you handle errors in a callback function?

Errors in callback functions are typically handled using the 'error-first' callback pattern. The first

argument of the callback is reserved for an error object. If an error occurs, it is passed to the

callback; otherwise, null is passed.

Example:

function doTask(callback) {

let error = true;

if (error) {

callback('An error occurred', null);

} else {
callback(null, 'Task completed');

doTask((err, result) => {

if (err) {

[Link](err);

} else {

[Link](result);

});

You might also like