I am looking for a way to execute multiple functions in JavaScript and force them to run sequentially. The most straight forward way to achieve this is to use callback functions (which has been the most commonly found suggestion on this forum and elsewhere). The problem with callback functions is that the resulting code can easily become hard to read as the result may be a lot of nested callback functions.
Am wondering if the following code will execute sequentially as well:
function doSomeThingOne(){
//do something intense here that takes quite some processor time
void(0); //dummy statement for illustration purposes only
return true;
}
function doSomeThingTwo(){
//do something intense here that takes quite some processor time
void(0); //dummy statement for illustration purposes only
return true;
}
function testSequentialExecution(){
//a temporary variable just to capture the
var bolTemp=false;
//execute the first function
bolTemp=doSomeThingOne();
//after this is done, execute the second function
bolTemp=doSomeThingTwo();
}
//kick off the (hopefully) sequential execution
testSequentialExecution();
Am looking for a plain JavaScript solution.
If my functions doSomeThingOne() and doSomeThingTwo() do not execute code that runs a-synchronically (like a typical AJAX request) will this coding-style force the functions to execute synchronically?
Yes, of course. That works just the same way JavaScript doesn't shuffle the content of any other function - expressions in a function will always be executed in order. Specifically, all expressions inside of a code block (something between {}) will always be executed in order. A function body is such a code block.
The expression might have async side effects (like calling setTimeout() or making AJAX calls) but the expression itself is evaluated in order. The browser can just determine to keep references to part of the expression and execute those parts later.
Your question seems like you spent too much time in the async world ;-)
The main problem is usually that you do something async. And then, the function ends and eventually, the callback will be called. There is no good way to serialize this. Maybe JavaScript promises will help.
Related
See the below code
vat t = setTimeout(x, 1000);
vat t1 = setTimeout(y, 1100);
var t2 = setTimoue(z, 4000);
The order of execution is t, t1 and t2. So, t is executed after 1s. Till here is fine. Then is t1 executed after 100ms(1100 - 1000) or is it executed 1100ms after t is executed?
t1 will be executed 100ms after t was executed.
But actually, if the page is busy, setTimeout may be fired later so that it can less or greater than 100ms.
Above is the correct answer, although I would encourage you, going forward, when possible, to go open up the JavaScript console in your browser and figure it out yourself. console.log(Date.now()) in your code and test it. When I first got into coding, I would always turn to pros for simple questions (out of habit), but in my experience, being successful in coding often means knowing HOW to get the answer, as opposed to just knowing WHAT the answer is.
Additionally, I would argue you're much more likely to remember the answer if you identified it yourself instead of someone just telling you.
Good luck!
If you want to control the order of execution I really think you should sequence the timeouts.
var t = setTimeout(x, 1000);
function x(){
setTimeout(y, 100);
}
function y(){
setTimeout(z, 2900);
}
In any case I'm not sure you should be doing any of this in the first place.
If you want to call one function after another just use the .call or .apply.
take a look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
JavaScript is single-threaded. If some block of code uses execution thread, no other code can be executed. This means your setTimeout() call must wait until main execution finishes.
[from here]setTimeout behaviour with blocking code
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.
Is it possible for me to pass a callback parameter to another method from within the callback function block itself? Example:
var resultCallback = function(result){
if(result)
{
alert('success!');
}else{
callServiceB(resultCallback );
}
}
callServiceA(resultCallback);
The reason of this is i wish to workout something like a Chain of Responsibility patterns in javascript.
Tried googled but so far gets nothing. Any idea or comment is welcomed.
Is it possible for me to pass a callback parameter to another method from within the callback function block itself?
Yes you can. Try it!
I wish to workout something like a Chain of Responsibility patterns
Putting both the responsibility chain (callServiceB(resultCallback)) and the resulting action (alert('success!')) in the same function looks like a bad practise/design smell. You should use an extra callback for the result, and separate the declaration of the chain from that.
It might then look like callServiceA(orCallServiceB(alertResult)) or either(callServiceA, callServiceB, …)(alertResult).
The logic is like 1. call function a 2. if function a ok, then call function b 3. if function b ok, then call function c, and so on.. – ipohfly 8 mins ago
That doesn't sound like a chain of responsibility, where you call the next function only if the current one failed (couldn't process the arguments)? What you describe sounds more like monadic chaining (one action relying on the previous one) - take a look at promises for that:
callServiceA.then(callServiceB).then(…).then(resultCallback);
So I started learning javacript and I've noticed that the coding convention for functions and callbacks is something like this (this is a jQuery example but I've seen these everywhere):
$.getJSON('some/url.json', function(a) {
// do stuff with a here
});
Coming from other languages, I would usually write the above as this:
function myFunction(myVar){
//do stuff with myVar here
};
$.getJSON('some/url.json', myFunction());
Why is the former usually the preferred way of writing in JS, instead of the [probably more readable] latter?
There are plenty of good reasons to use the second, more explicit, format (assuming you fix the issue listed in the comment), including:
reusing the function passed as a callback
giving that function a definitive name to make it easier to debug
making sure that function is noted as something important in your system
separating out that functions because it's simply too long to comfortably declare in place
But the first format, with an anonymous function passed as a callback is short and sweet. If you don't need to reuse the function, if it's relatively short, and if it's not of high importance in your system, it can be really useful to declare it exactly where you use it. You avoid adding another variable to your scope, and you make it entirely clear exactly what that function is for.
It's not the preferred way. You can do anything you want. However, if you need to reuse the function, then you need to do your second option, or alternatively the following, for code reuse:
// in some accessible context/namespace
App.myCallback = function(a){
...
};
// somewhere else
$.getJSON('url', App.myCallback);
Your first example is what is referred to as an anonymous function or block. They are used when they'll only be called once. The second example is when you'd use the function many times... it would be a lot of wasteful typing if you repeated the anonymous block over and over.
With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.
EDIT: It seems that parsetime is the wrong word. I guess I should have formulated the question "In the 2-pass read, what gets read the first pass and what gets read the second pass?"
A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:
foo();
function foo() {
return 5;
}
but the following doesn't
foo(); // ReferenceError: foo is not defined
foo = function() {
return 5;
}
However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.
Unlike C++, it is not possible to run logic in the Javascript parser.
I suspect that you're asking which code runs immediately and which code runs when you create each object instance.
The answer is that any code in a function that you call will only run when you call the function, whereas any code outside of a function will run immediately.
Not sure what you ask exactly so I'll just share what I know.
JavaScript functions are "pre loaded" and stored in the browser's memory which means that when you have function declared in the very end of the page and code calling it in the very beginning, it will work.
Note that global variables, meaning any variable assigned outside of a function, are not preloaded, so can be used only after being declared.
All commands outside of a function will be parsed in the order they appear.
JavaScript doesn't really have "runtime", it can only respond to events or have code executed via global timers. Any other code will be parsed and "forgotten".
While JavaScript's direct ancestor is Scheme, JavaScript didn't inherit macros, so the answer is fairly simple: there is never any code run during parse time.
Roughly speaking, Interpreter gets all variables and functions first, and then they get hoisted and executed.
For more detail, I hope these links might be helpful:
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting
https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/