One problem that may arise using these functions is when we want to call a function defined somewhere else and pass a parameter to it. If we try to do the following:
var myFun = function(param) { //do something } var myParam = 'parameter'; setTimeout(myFun(myParam), 1000);
Instead of executing the function after 1000ms, it will execute it immediately. This is because the compiler first interprets the function calls, like myFun(myParam), and then passes the result as the callback to the setTimeout function. To avoid this, the usual way is to pass function as a variable, thus omitting the parentheses. This of course leads to one problem: how to pass parameters to the callback function? It is done in the following way:
var myFun = function(param) { //do something } var myParam = 'parameter'; setTimeout(myFun, 1000, myParam, ...);
The three dots there indicates that each following input parameter will be treated as an input parameter to the callback function. The same concept applies for the setTimeout function.
ReplyDeleteService calls
ReplyDeleteEnjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck for the upcoming articles Nodejs training