I am new to JavaScript and I work in node, which requires a good understanding of asynchronous programming and callback. I found that using built-in functions is very simple, even when your callbacks have several levels. Your built-in callbacks just end in closure.
However, if you have several levels of callbacks in which many callbacks are similar to execution routes, you end up rewriting a lot of callback code over and over in separate callback chains. For example, if the definitions mycb1 and mycb2 below move outside A, they no longer have implicit access to A variables and therefore no longer function as closures.
An example with built-in definitions where they function as closures.
mod.A=function(){ var mycb1=function(err){ if (!err){ var mycb2=function(err){ cb(err); }; mod.foo2(args,mycb2); } else{cb(err);} }; mod.foo1(args,mycb1); } mod.foo1 = function(args,cb){
I want to do the following, but be able to change the scope of the variables for the functions mycb1 and mycb2 so that they can be used as a closure from where they are called. For example:
var mycb2=function(err){ ... cb(err); }; var mycb1=function(err){ if (!err){ mod.foo2(args,mycb2);
I know that I can implement a project that either sets a variable at the mod level so that they are available for mod level functions. However, this, apparently, somewhat pollutes the region of the mod variable, which can be used only by a few of its "methods". I also know that I can pass variables to make them available for callbacks when they are executed. However, if I understand how JS and callbacks work, I have to pass them to fooX and then redirect them to callbacks. This also doesn't seem like a good plan. Is it possible to change the scope of a variable so that it acts as a closure from the point of its execution, and not to its definition point? If not, what is the best way to modulate your callback code?
rss181919
source share