Tuesday 24 November 2015

Understanding parameters to anonymous callback functions

Reddit,Getting up the curve on Node.js and trying wrap my head around anonymous callback functions. I understand conceptually how they work and when to use them, but not syntactically.I'm going to use snippets of the default chat app at Cloud9 which I'm trying to understand.My question is - how do you know the # and order of parameters to include in an anonymous callback function for the parent function?For example:messages.forEach(function (data) { socket.emit('message', data); }); It seems to me here that the '.forEach' passes each item of the array as 'data' into our anon callback fn, and then our anonymous function does something with 'data'. Why is there only one parameter to our anonymous function?If I look at MDN (http://ift.tt/15Q6Ehi) for a description of forEach, it seems that the callback should have three parameters (currentValue, index, array). So why does this code snippet only need one? If the answer is 'you didn't need nor include the second two so they were ignored', then why does this snippet of code note work:messages.forEach(function (data,index) { socket.emit('message', index); }); Similarly, the snippet below as part of socket.io: socket.get('name', function (err, name) { var data = { name: name, text: text }; Is it correct if I say: socket waits around until it ".get"s something, and if that something is a 'name', it takes that something and passes it to the anonymous function which has parameters 'err' and 'name'. How did we know to make our anonymous function have two parameters and that the first will be the error returned (if any) and the second will be the value of the something (in this case, the name)? Is there documentation somewhere for socket.get which states its anonymous callback function should always have these two parameters? If that's the case, I'm having trouble finding it.I guess my overarching question is that, as I read more code that others have written, anonymous callback functions seemingly have an arbitrary number of parameters, with seemingly random names and orders. For example, why not (name, err) in the above... why is err first?Thanks in advance.

Submitted November 24, 2015 at 06:06PM by oldmanandthebanker

No comments:

Post a Comment