Monday 9 December 2019

Javascript Callback with Parameters and Return Value



Here is my dilemma, I have a series of functions that get called and I am using callbacks to execute a function when they are complete. The callback returns a value and that works great too, my problem is when I add parameters to the callback I can no longer access the returned value. Here is an example what works:




function myFunc1(x, y) {
/*do stuff*/
myFunc2(z, callback);
}

function callback(results) {
alert(results); /*this works!*/
}



This works great, the results returned are displayed. My problem what I need to do is something like this:



function myFunc1(x, y) {
/*do stuff*/
myFunc2(z, callback(x,y));
}

function callback(x,y,results) {
alert(x); /*works!*/

alert(y); /*works!*/
alert(results); /*doesn't work :(*/
}


I need a way to access both the value return as well as my parameters. Is something like this possible??


Answer



You will need to not call the callback immediately, but instead make a function that calls callback later with the expected arguments:



function myFunc1(x, y) {

/*do stuff*/
myFunc2(z, function(results) {
callback(x, y, results);
});
}


The .bind() variant proposed by @thefourtheye is basically1 a shortcut for this function expression.



1: rather for function(results) { return callback.call(null, x, y, results) }, also it would pass through more arguments than only results, and it would evaluate x and y at the time of the bind call.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...