I'm currently learning about callbacks in Node and JavaScript in general and am getting confused by the following:
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.
}
})
My question is this: How does the request function know what each parameter/argument is in the callback? Because I could effectively call the function callback with two parameters and skip out the error? How would the function know that the first parameter passed was the response and not the error, for instance?
Does it do checks on the types of each at runtime or? Thanks.
The programmer who wrote the request API decides the order of the parameters sent to the callback. There is no type checking at runtime. If you were to supply only two arguments in your callback signature, e.g.
function(response, body) {}
you would still be receiving the error object and the response -- only in this case, the variable named "response" would hold the error object, and the variable named "body" would hold the response. The input you would be skipping would be the third one you didn't supply, the body. The names of your parameters make no difference, it is their position in the function signature that determines what value they will be assigned.
By convention, in javascript callbacks, the first parameter of the callback normally represents the error object. It is not always written this way, but it is a best practice.
Possibile implementation of this function could be:
function request (url, callback) {
// doing something
callback (error, response, body);
}
The function will set the value of error
, response
and body
parameters. I don't know how it's is implemented, but suppose that you pass a number for the url
. A possibile implementation could be:
function request (url, callback) {
if (typeof url === 'number') {
// Suppose that error is an instance of Error
callback (new Error ('Url must be a string'), null, null);
}
// other stuff...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With