I have had trouble understanding the rules concerning callbacks in javascript. I understand that callbacks run after function x finishes however I find there is ambiguity when defining them.
In the node.js docs : https://nodejs.org/en/knowledge/getting-started/control-flow/what-are-callbacks/
The code
function processData () {
var data = fetchData ();
data += 1;
return data;
}
is changed to
function processData (callback) {
fetchData(function (err, data) {
if (err) {
console.log("An error has occurred. Abort everything!");
return callback(err);
}
data += 1;
callback(data);
});
}
when the anonymous function is created why can we use parameters, where do these arguments come from, what rules regard these parameters?
The context of this question comes from the sockets.io library Specifically:
var io = socket(server);
io.on('connection', function(socket){}
Why can we reference the socket, can I just add in function(random_param, socket)? What tells the function to reference when passing random_param?
I was told read the docs, which I had already done but that didn't make things any clearer.
Thanks in advance.
forEach's callback, for instance, ormap's, orsort's, or...io.on(eventName, callback)determines what is passed to that callback when it is called. You can't randomly change itfetchDataandio.onclearly expect functions as those parameters, and presumably document how and when they will be called, including with which arguments.