javascriptasynchronousnode.jsfunctional-programmingserverside-javascript

JavaScript callbacks and functional programming


"Functional programming describes only the operations to be performed on the inputs to the programs, without use of temporary variables to store intermediate results."

The question is how to apply functional programming and yet use async modules that utilize callbacks. In some case you had like the callback to access a variable that a function that invokes the async reference poses, yet the signature of the callback is already defined.

example:

function printSum(file,a){
     //var fs =....
     var c = a+b;
     fs.readFile(file,function cb(err,result){
          print(a+result);///but wait, I can't access a......
     });
}

Of-course I can access a, but it will be against the pure functional programming paradigm


Solution

  • fs.readFile(file, (function cb(err,result){
        print(this.a+result);
    }).bind({a: a});
    

    Just inject context with variables and scope into the function if you must.

    Because you complain about the API

    fs.readFile(file, (function cb(a, err,result){
        print(a+result);
    }).bind(null, a);
    

    It's called currying. This is a lot more FP.