Getting a Better Understanding of Callback Functions in JavaScript

Getting a better understanding of callback functions in JavaScript

You can just say

callback();

Alternately you can use the call method if you want to adjust the value of this within the callback.

callback.call( newValueForThis);

Inside the function this would be whatever newValueForThis is.

Getting a better understanding of callbacks with Node.js

In your code: usingItNow(myCallback);

You are invoking the function usingItNow and passing it function myCallback.

Inside usingItNow you are executing your parameter callback by doing this callback('From Using it') you are essentially doing myCallback('From Using it') because callback is equal to myCallback.

You don't need to return anything because myCallback is doing the logging.

Your camel case is fine.

Understanding callback function purpose

In simple terms you can say a callback is a way of asking a question (or requesting a task) in advance, i.e. when you're done with this do this (usually with the result). The whole point is to set aside functions that are to be done later, usually because you don't have the required inputs to do them now.
The 2 main differences between your implementation and the MDN one is that yours is harder to maintain and harder to reason about hence test.

1. Maintanance / Reusability

Imagine you're a few thousand lines of code into a code base then you're required to change what processUserInput() does. Its much easier to change or write a new callback function instead of changing the function processUserInput(). This would be evident if processUserInput was a bit more complicated. This also means the MDN one is much more useful in various scenarios unlike your implementation. You can reuse it in different situations like saying good bye, capitalizing names etc simply by writing different callbacks to plug into processUserInput().

2. Testing / Easier to reason about

The MDN implementation is much more easier to understand. Its easier to assume that the function processUserInput(greeting) will probably return a greeting than it is to assume what processUserInput() does. This makes it easier to test because you can always be sure the MDN implementation will always return the same output given an input.

Having a difficult time understanding callback functions

One way to do this would be to use JS Promises like so

function getItems() {
return Promise.resolve(
$.get(url,
function (data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function (ele) {
return ele;
})
return itemArr;
}));
}

function alertTest() {
var items = getItems().then(function (items) {
alert(items);
});
}

It is a hard one to get your head around. Promises allow you to write code that runs in a sequence like sync code.

You could insert callbacks into the function and have that call when the get request finishes like shown in the other answer by Rhea but this is a cleaner way to do this and Promises are now part of the Javascript language.

Wanted help in understanding how parameters are defined in Callback functions, using this example (if possible)

You pass a function in to readFile, and later on readFile will call your function. When it calls your function, readFile will pass in the relevant values.

You can do something similar yourself, like this:

function myReadFile(filename, callback) {
setTimeout(() => {
if (Math.random() > 0.5) {
callback(null, 'fake file');
} else {
callback('an error', null);
}
}, 1000);
}

myReadFile(`${__dirname}/temp.txt`, (err, data) => {
console.log(`Breed: ${data}`);
})

(though of course the real readFile function isn't doing timeouts or random numbers, but rather reading from a file and listening for that operation to succeed or error out)

Understanding Callbacks

Imagine get implemented more or less like

function get(url, callback) {
var response = they somehow retrieve the response;
var body = they somehow parse the body;
var error = ...;

// they call you back using your callback
callback( error, response, body );
}

How these values are computed is irrelevant (this is their actual job) but then they just call you back assuming your function actually accepts three arguments in given order (if not you just get a runtime error).

In this sense they also kind of "accept" your callback by ... well, calling it back :) There is no worry about the number of arguments as Javascript is very "forgiving" - methods can be called with any number of arguments, including less or more arguments than the function expects.

Take this as an example:

// they provide 3 arguments
function get( callback ) {
callback( 0, 1, 2 );
}

// but you seem to expect none
get( function() {
});

The get assumes that the callback accepts three arguments while I pass a method that supposedly doesn't accept less arguments. This works, although the three arguments, 0, 1 and 2 are not bound to any formal callback arguments (you can't directly refer to them), they are there in the arguments object, an array-like structure:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

Take another example

function get( callback ) {
callback( 0, 1, 2 );
}

get( function(a,b,c,d,e) {
});

This time the callback I pass seems to expect more arguments than the caller provides and still, no problem here. Arguments are bound to consecutive call parameters, a will get 0, b will get 1, c will get 2 and d and e will get undefined inside the callback body.

Both examples show that the caller doesn't really care how your callback is defined, whether its number of arguments matches the expectation or not. In case of any mismatch, the worst what could happen is a runtime error:

function get( callback ) {
callback( 0, 1, 2 );
}

get( 1 );

// Uncaught TypeError: callback is not a function

Examples of efficient use of callback functions

A callback is usually used when you have to deal with a function (or method) which you don't know how much time could take to compute.

For example, assume you need to get some water from a shaft to do something, but you don't actually know where and how far this shaft is from your house: you ask a friend (asynchronous function) to kindly walk to the shaft and take the water for you, so that when he comes back you can use it.

In the mean time, while waiting for the water, you could have done some other useful things.

A basic example of that would be:

function getWater(callback) {
// Walk to the shaft
// Take water
// Go back home
// This function is asynchronous

callback();
}

function useWater() {
// Do what you needed to do with water
}

getWater(useWater);
// While waiting to use the water:
doUsefulThings();


Related Topics



Leave a reply



Submit