Search code examples
javascriptcallbackargumentswrapperfunction-binding

How to re-bind() the same function in Javascript?


I am writing a wrapper that accepts a callback function to pass on to another function or execute directly. The problem is that another functions have bound parameters with callback parameter having a different argument number. Therefore initial binding would accept a string placeholder that needs to be replaced. But how?

function callback(){}

function asyncfunc1(a,b,callback,d){ callback();}
function asyncfunc2(a,b,c,callback){ callback();}
function asyncfunc3(callback,b,c,d){ callback();}

function wrap(cond,func,callback){
    if  (cond) {
        // here I want to execute the passed function
        // however instead of real callback, I have a placeholder bound
        // so how do I bind it again to replace it with real callback?
        func(); 
    }
    else callback();
}

wrap(cond,asyncfunc1.bind(null,param1,param2,'callback',param3),callback)

// this is what it's used for, is to create a flow of conditional callbacks

wrap(cond1,asyncfunc1.bind(null,param1,param2,'callback',param4),function(){
    wrap(cond2,asyncfunc2.bind(null,param1,param2,param3,'callback'),function(){
        wrap(cond3,asyncfunc3.bind(null,'callback',param2,param3,param4),callback
    }
})

Solution

  • I am going to avoid bind and pass a function with arguments as an array.

    function wrap(cond,fn_arr,callback){
        if  (cond) {
            if (fn_arr instanceof Array){
                var func=fn_arr.shift();
                if (fn_arr.includes('callback')) {
                    fn_arr[fn_arr.indexOf('callback')] = callback;
                }
                func(...fn_arr)
            } else fn_arr();
        }
        else callack();
    }
    

    Then with little array manipulation will do the replacement trick.

    wrap(cond,[asyncfunc,param1,param2,'callback',param4],callback)