Friday, 28 April 2017

Making local variable accessible by creating callback default value parm

function foo1(var1, var2) {        
    foo2(var1, function(result){
        console.log(var2)             
    });   
}         

As far as I understand the code above would return a typeError saying that var2 is undefined. The general solution I found is passing the desired variable (var2) to foo2 and change foo2 to send var2 to the callback. This will work but changing foo2 to accommodate the need of one function isn't, I think, a good solution, because it makes foo2 lose it generic purpose.

I thought that doing something like change callback function to include var2 as a default value would solve:

function foo1(var1, var2) {
    foo2(var1, function(result, var2=var2){
        console.log(var2)             
    });   
} 

This way, when foo2 call the passed callback function, it wouldn't need to send the third parm once once this has a default value defined. But this doesn't seem to work. Can anybody help me to found the best approach?

I'm perhaps asking a basic question but, please, bear in mind that I'm very new to node and js world in general.



via mar

No comments:

Post a Comment