Sunday, 14 May 2017

NodeJS: Higher Order Function to Create Higher Order Function with Callback

As I have learned a little more about NodeJS and callbackHell I am trying to include more and more higher order functions in my project. One idea I had was to make a function that creates other function in a manner that is suited to callback.

My approach looks like this:

function putFunctionInFunction(func, funcTwo) {
const tempFunc = function (callback) {
    func(() => {
        funcTwo(callback);
    });
};
return tempFunc;

}

Following that my plan was to use this function to make a big-callback function out of an array of functions.

That functions looks like this:

function callbackFunctionArray(arr) {
let tempFunc = function (callback) {
    callback();
};
for (const func of arr) {
    tempFunc = putFunctionInFunction(tempFunc, func);
}
return tempFunc;

}

Sadly my first function does not work and I can not get my head around the reason why. It only produces 'undefined'-results. What I am guessing so far is that the function that I wanted to save in tempFunc is immediately evaluated and produces the 'undefined'-error.

My questions are this:

  1. How can I realize my putFunctionInFunction-function without using other modules?
  2. Is anything wrong with my second function - probably in the same area?
  3. Is there a approach to combining functions that is better and/or different than mine?

Thanks for the help.



via luccr1

No comments:

Post a Comment