AmouxTechnerd AmouxTechnerd - 2 months ago 9
Javascript Question

How to pass values to a nodejs callback

So I'm trying to wrap my head around how i can pass variables/data to a callback sort of like how Request does it:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})


how do the developers pass the error, response, and body to the callback for the user to use? For instance, say I have a basic main function:

function main(_arg1, _arg2, callback) { ... }


and when i call it i would do something like

main('test1', 'test2', function(a, b){ console.log(a+b); }


correct? So how would i pass
_arg1
and
_arg2
to the callback so that it would output a result like
test1test2
?

I tried looking all through stackoverflow but i couldn't find anything relating to this, so if this is a duplicate I'm sorry.

However, any help and/or explanation would be greatly appreciated! :)

Answer

You just pass them as arguments when you call the callback. Here's an example:

// define a function that accepts a callback argument
function callMeBackPlease(x, y, callback) {
    // call the callback and pass it the desired arguments
    callback(x+y, x/y);
}

// call the function and pass it a callback function
callMeBackPlease(3, 5, function(sum, div) {
    console.log(sum, div);  // outputs 8, 0.6
});

A callback is just a function. And, in Javascript you can pass a function as an argument when calling some other function and the function it was passed to can then call that callback function with whatever arguments are appropriate.

Comments