CLI NodeJS (Concurrency, Callbacks, .methods) - javascript

Just a couple of questions regarding using Nodejs in Web Development.
1) For my Concurrency question, it regards syntax. Is there a difference between:
setInterval(function() {
console.log('Task A');
}, 10);
and
function setInterval() {
console.log('Task A');
}, 10);
Also, i'm a little confused what the '10' means at the end of the method, my guess is the time it takes for the method to complete?
2) Callbacks - Are Callbacks just technically another name in Node for testing code?
3) Is there a method I can use in the Node(CLI) to see all of the methods in a module?
EX:
var fs = require('fs');
Obviously there are tons of methods in the File Systems module, but like the language Ruby, using PRY in the CLI, you can type 'fs.methods', which will display all of the methods. Then using 'cat', you can see the contents of each individual method. Something like this for Node(CLI)?
Thanks for all of the advice/answers!
Cheers,
G

1.
In the first, you pass in an anonymous function which will be invoked at the interval. Here you are using the node.js API setInterval.
In the second example, you are declaring a function called setInterval. Looks like a syntax error is there...
setInterval is a function that takes 2 objects in as parameters. That's it. the first parameter should be a function, and the second parameter should be a the the interval time in milliseconds. All that setInterval does is run the function passed in in the first parameter(a callback) every x milliseconds as specified in the 2nd parameter.
2.
No. Callbacks are functions that can be passed to other functions so that they can be "called-back" later in the code. Callbacks are pervasive in node.js applications and tightly related to it's asynchronous event based architecture. It is one of the most common patterns seen in node.js.
3.
Just look in node.js api docs on their website.
My recommendation to you would be to read about the node.js event loop and asynchronous programming.

First off, you're asking about some pretty fundamental aspects of Javascript so I'd suggest you work though some basic Javascript training because it will be hard to learn node.js if you don't already have a core understanding of the basics of Javascript. In particular callbacks are integral to much of nodejs coding.
Is there a difference between these two?
Yes, the two are completely different. One uses a built-in timer function, the other attempts to declare it's own function that has nothing to do with timers.
Let me explain your two examples:
The built-in setInterval function
setInterval(function() {
console.log('Task A');
}, 10);
Nodejs has a built-in timer function called setInterval. You can find the doc for it here.
You pass this function two arguments. The first argument is a function reference, the second argument is an amount of time in milliseconds. The nodejs timer infrastructure will call the function you passed it every N milliseconds.
It might be slightly easier to understand how setInterval works by seeing it used like this:
function myFunction() {
console.log('Task A');
}
setInterval(myFunction, 10);
This has the same output as your first example, but I think it shows more clearly how setInterval() is a built-in function that takes two arguments, a function and a number.
In your example, instead of the named function you are passing an anonymous function that simply does console.log('Task A'); and that function will be called every 10ms (approximately).
Create Your Own Function
function setInterval() {
console.log('Task A');
}, 10);
This block of code is a Javascript Syntax Error and will not work. It looks like you're attempting to define your own function called setInterval(), but this is not the proper syntax for declaring a function.
You could make it legal syntax like this:
function setInterval() {
console.log('Task A');
}
And, then you would call it like this:
setInterval();
This has nothing to do with the previous example. This just creates a function that runs once each time you call it. If you actually gave it the same name as the global function setInterval(), then your local definition would replace it within the scope it was declared.
Your Other Questions
Also, i'm a little confused what the '10' means at the end of the
method, my guess is the time it takes for the method to complete?
The 10 in the first example is the number of milliseconds for the interval timer. The 10 in the second example does not belong there - it's part of a Javascript syntax error.
Callbacks - Are Callbacks just technically another name in Node for
testing code?
No. A callback is when a function takes an argument that is a function reference (e.g. the name of a function or an anonymous function). When you pass a callback to this function, you can expect that the function will call the callback one or more times at some time in the future. When exactly it is called or how many times it is called depends entirely upon what the function does and how it is written. The term "callback" comes from the notion that this function will be "called back" some time in the future.
Is there a method I can use in the Node(CLI) to see all of the methods
in a module?
I'm not aware of a specific feature in the command line interface that will give you the methods of a module, but you can iterate them yourself or look at them in the debugger.
When you load a module in node with something like:
var fs = require('fs');
The object you get back from the require() function is a Javascript object. All the methods of that module are properties on that object. You can inspect that object in the debugger or with console.log(fs) or by writing code to iterate the properties of that object.
var fs = require('fs');
for (var prop in fs) {
if (fs.hasOwnProperty(prop)) {
console.log(prop);
}
}

Related

strange way of passing arguments in express.js source code

When I was looking for source code of express router i saw this:
var debug = require('debug')('express:router:route');
can someone explain what this way of passing arguments mean?
In Javascript, functions are "first class", meaning they can be passed around like any other values.
require('debug') returns a function. As in, the default export of the debug npm package is a function, not an object.
That function is then called with the string "express:router:route"
A function that takes in some state or config, and returns a function based off that state or config, is partial application. This isn't a case of partial application, though, it's just a shorthand for:
var debug = require('debug');
debug('express:router:route');
require isn't a function that's meant to be partially applied, it just means that the debug package is returning a function, and it's being executed in place.
This is a technique as a part of functional programming, called currying, where the function has two arguments, and you can pass the first one and the second one separately.
It is a little hard to get your head around, but worth studying
What is Currying?
Currying is a process in functional programming in
which we can transform a function with multiple arguments into a
sequence of nesting functions. It returns a new function that expects
the next argument inline. It keeps returning a new function (that
expects the current argument, like we said earlier) until all the
arguments are exhausted. The arguments are kept "alive"(via closure)
and all are used in execution when the final function in the currying
chain is returned and executed.
More info here: https://blog.bitsrc.io/understanding-currying-in-javascript-ceb2188c339
Take a look at the debug package (link):
debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
So, require('debug') returns a function. That function can be called by doing require('debug')(some parameter). Which means the following is possible (example taken from the debug docs linked above):
var debug = require('debug')('http')
Now the variable debug points to the result of calling the function returned require('debug'), with the parameter 'http'.

Want to understand need of callback functions in javascript

I am new in learning JavaScript. I read about callback functions but I am unable to understand its real use.
So, please help by any real world example.
Below is small code depicting use of callback function in but that too is not clear to me.
var friends = ["Mike", "Stacy", "Andy", "Rick"];
​
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});
The uses of JavaScript callback functions are many. You probably already know that it's simply a function that we pass as an argument to another function. This means that we can have a function called foo. Lets says foo is some sort of method that runs an array through a sort, however the actual sorting function is variable. So we could use foo for every algorithm, by simply passing values like so.
foo([1,6,1,2], quickSort);
Assuming we have a quickSort method.
Generally speaking, callbacks are however used to call something AFTER a function has executed. So why not just call one function after the other, you say?
foo();
bar();
Why would you pass bar to foo ? Well, usually callbacks are used when dealing with asynchronicity. So, the bar function would get called way before, say an AJAX request gets a response, or before a setTimeout triggers it's callback.
As for the specific example you provided, it's simply a simplified way to iterate over an array. With the added benefit that you can use a named function, so you can declare it earlier and separate your code better.
Javascript is generally synchronous, i.e. commands are executed one after the other.
However there are times where you want a function to be asynchronous, so you call a function and don't want to wait for it to complete before you move on to your next task.
Callbacks are used by asynchronous functions. When the function completes, the callback function is run, without the rest of the code having to wait for it.
var friends = ["Mike", "Stacy", "Andy", "Rick"]; friends.forEach(function (element, index, array) { console.log((index+1) + "." + element ); });
The concept of Callbacks in JavaScript is that you can assign functions to variables.
Everthing, in JavaScript, except for simple types as string and number, are objects (and even those have functions to be called as they were objects as well).
Let's take your function for instance, as example:
Syntax
arr.forEach(callback[, thisArg])
Parameters
callback
Function to execute for each element, taking three arguments:
currentValue
The current element being processed in the array.
index
The index of the current element being processed in the array.
array
The array that forEach is being applied to.
thisArg
Optional. Value to use as this when executing callback.
It takes a callback function that will be called for each element.
Also, we have the definitions of asynchronous calls in JS (with a help of timeouts/interval and AJAX calls).
The idea of the callback functions doesn't stays just in JS. Anywhere it would be easier or just simples, to use a function passed as reference we have the concept of callback (it just goes insane with this feature of AJAX in js, that why it's so common to say JS is asynchronous).
You could read a litte more about it here:
http://www.sitepoint.com/javascript-goes-asynchronous-awesome/
In JavaScript, function below is an object:
function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
}
Let call this object A.
When you pass the code friends.forEach(A), browser will understand that when running through the array friends it will trigger A.
So at the end, callback function is just like you "define" function but you will use it later on.

If a callback calls the enclosing function, would it be called a recursive call?

For example:
If http.request call is made in res.on('end') callback, then is the call recursive?
http.request(options, function(res) {
res.on('data', function(chunk) {
data+=chunk;
});
res.on('end', function(){
//do some stuff
http.request(options, function(res) {...});//is this recursive?
});
}).end();
Edit:
Let's take a simpler example: suppose there is a function which reads a file character by character:
var noOfChar = 10;
var i = 0;
readChar(function processChar(char){
if(i < noOfChar) {
console.log(char);
i++;
readChar(processChar); //is this recursive?
}
}
Rather than arguing about what to label it, let's consider some concrete attributes of your code, and how it is similar or different to what people usually mean by "recursive".
Usually a recursive function is something that grows the stack at each step (except for tail-call recursion, which uses a trick to prevent that growth). But in node, an asynchronous callback discards the stack of the outside context. (Try raising an exception inside the callback and see for yourself.) So this code does not grow the stack.
Also usually a recursive function is something that calls itself, but I don't see that happening anywhere in your example. The two listeners on http are different functions.
The second example doesn't call itself directly, but it does call itself indirectly. You have a "base case" (noOfChar >= 10) at which point the recursion unwinds. If readChar were synchronous you'd even be growing the stack. So this seems closer to recursive.
Notice that in your second example you have a named function, whereas the first example has only anonymous functions. In general I don't think recursion is possible without a named function (or at least some variable that holds the function), because otherwise how can a function refer to itself?
I don't think it'll be recursive if you are going to pass a different callback to it.
If you will pass same callback to both, it is going to be recursive.
Recursive means if I'm calling the same function in function definition itself. But if you are going to pass different callbacks it will be something like bellow.
Suppose you have 2 different callbacks callback1 and callback2.
You have passed first callback to outer http.request and second callback to inner http.request, so outer http.request will be executing the code given in callback1 but the inner will be executing code given in callback2.
I don't understand the meaning of the question.
Will you be flogged to death by your boss if the answer is yes?
Is there a law against recursivity?
http.request is only a means to an end. One way or another, you will need to call it more than once to process a transaction.
The trouble with your example code is that you handle an asynchronous exchange in one big lump of code, which handles the response directly without tracking the state of the transaction.
The only comment that comes to my mind is that this kind of logic is extremely fragile, because the termination conditions are dependent on whatever parameters are passed to your requests, leaving the door open to a score of potential problems like out of sync answers and infinite loops (whether they deserve the name of "recursive calls" is of little interest if they hang the system in the end).
I would rather advise to build an explicit state machine to track the progress of intended HTTP exchanges, which would dispense of philosophical questions about recursivity and the associated "good practices".
I'm going to try to answer my own question because I think now I understand Recursion a bit better. Maybe this will help someone else.
My doubt was if a function invokes a callback, which calls the function again would it be called recursion. I feel it is similar to indirect recursion where function1 calls function2 and function2 calls function1 again. So it doesn't matter if function1 calls function2 which calls function3 which in turn call function1 again, it is still recursive. In the same way it shouldn't matter if function invokes a callback which invokes another callback which calls the function. If second example is recursive, first can also be recursive.
Recursive solution to a problem has to do more with how the problem is solved than the language implementation like growth of stack. Take tail-recursion for consideration, it doesn't increase call stack, yet no ones questions about it's recursiveness.
So the key point is to think recursively. Take the whole problem, if a part of it can be solved in the same way as the original problem then the solution is Recursive. A function calling itself may not qualify for being recursive. Some may call it self referencing functions but not recursive.
Recursion should at least consist of a base case and a recursive case, each self-reference should bring the input value closer to the base case which would end the recursion.So I think both of the examples mentioned in the question are not recursive.
Recursive calls may not result in increase in call stack. There is tail call recursion which keeps call stack size constant.
Take the following examples which consist of callbacks, here outer function stack frame may or may not be in memory.
var input = [[1,2,3],[4,5,6],[7,8,9]];
function double(ip) {
return ip.map(function (element) {
if(Array.isArray(element)) {
return double(element);
}
else {
return 2 * element;
}
});
}
console.log(double(input));
I would call it as recursive. Also we can do Anonymous Recursion, so explicitly naming a function isn't necessary.

How does "makeAddFunction" in Eloquent JS work?

I'm trying to learn Javascript by reading Eloquent Javacript. I'm on the chapter dealing with functions and I'm stuck trying to figure out how the code below works. I don't see how the add function ever gets called. I see them calling addTwo and addFive but those names are different than add. The result of this code being run is 9. Can someone please explain this to me.
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
In makeAddFunction, a function is created, called add. This function is returned.
makeAddFunction is called twice with 2 different parameters, and stored in two variables, addTwo and addFive.
Calling addTwo() and addFive() is calling the functions created by add(), with the "amounts" 2 and 5 respectively.
addTwo(1) + addFive(1) == (1 + 2) + (1 + 5) == 9
Sometimes these types of 'closures' are called Builders, or Factories. The makeAddFunction 'builds' a special version of add based on the parameter you pass to makeAddFunction.
The addTwo function would look like:
function addTwo(number) {
return number + 2;
}
The makeAddFunction create a closure that sets amount as whatever number you pass in and returns a function that will add that amount to whatever number you pass to the new function and return it.
My best advice is you try to learn a bit about Javascript closures. Really. I might not be the answer you are looking for, but it is the best you can do if you want to understand what's happening there.
Get yourself a copy of any good javascript book. Let me suggest 'Javascript - The Good Parts' by Douglas Crockford.
For some of us, Javascript closures were not something we grokked. I hope it's easier for you.
Anyway, makeAddFunctionis a function creator. It creates new functions which are tied to the parameter you passed to makeAddFunction. Therefore, the addTwo variable receives and stores a new function, which you can invoke later by appending parentheses to it, i.e. addTwo().
The parameter you pass to addTwo, i.e. 1on invokation addTwo(1) is passed to the add function, because addTwo is nothing more than an add function where the amount var has a fix value of 2.
var addTwo = makeAddFunction(2);
When you call makeAddFunction(2) initially, the amount var is within its function scope where add can see it. addTwo now is set to the add function that makeAddFunction(2) returned.
addTwo(1)
Remember addTwo is now set to what makeAddFunction(2) returned, which is the function add, and amount is set to 2 within makeAddFunction(2)'s scope. add just returns its argument (1), plus the amount (2) in makeAddFunction(2)'s scope.
The same goes for addFive(5).
Javascript Ninja or The Good Parts are good reads that explain closures in detail. I'd highly suggest picking up those.
Follow the SO Linked/Related Questions on the right. Anyway ..
This is explained the article, albeit with a lot of fluff. Anyway, with a bit of fluff-cutting here is a "annotated" version:
.. functions [do] not just package up [some code to run], but also an environment. [..] a function defined inside another function retains access [to lexical variables (like "amount")] that existed in [the outer function] at the point when [the inner function] was defined.
Thus, the [inner] add function in the above example, which is created when makeAddFunction is called, captures an environment [including the "amount" variable of the outer function]. It packages this environment, together with [the code to run], into a value [(which is a fancy way to say functions are just objects)], which is then returned from the outer function.
When this returned function ([which has been assigned to] addTwo and addFive) is called, [the called function has access to] the captured environment ([and the "amount" variable which still contains the value initially passed to makeAddFunction]). These two values ([which are currently named by] "amount" and "number") are then added, and the result is returned.
I am not found of the original usage of "value" and have edit those parts a good bit - in JavaScript, variables (not values) are bound in closures.
Javascript relies pretty heavily on higher-order functions. Functions can be returned, assigned to variables, and passed around as values. This comes in handy in a lot of situations, especially when dealing with evented programming (JS's direct lineage from the its most prolific implementation in the browser.)
http://en.wikipedia.org/wiki/Higher-order_function
What you are seeing is a function that creates a function. It could be considered a "factory" for a function with one preset argument.

JavaScript Patterns: Context of Function Call

I have a ton of JavaScript from the dawn of time with function calls written like this:
THING.someFunction.call(THING);
It seems to me that should always be equivalent to:
THING.someFunction();
Are these two calls always equivalent? What about old versions of JavaScript?
It seems to me the purpose of the second THING in that first line of code is to set the context (this) inside someFunction. But the context inside that function should already be THING by default, right?
Just to be clear, THING is defined something like this:
var THING = function () {
// private vars
return{
// code
someFunction : function () {
// code
}
};
}();
Yes, they are equivalent. And I don't know any version of JavaScript in which they were not (however, call seems to have been added in 1.3).
They are the same technically. But they also behave slightly different in asynchronous programming. call() is used to call a function by passing a scope as the parameter. This provides a convenient way to call defined functions in callbacks and delayed execution (setTimeout, setInterval). If you have used any of the JS libraries, you would have noticed $.proxy, or _.bind, these are aliases that implement call(scope);
See this MDN doc for more info.

Categories

Resources