Isabell
asked on
number of parameters in callback
Hi,
I have a main easyhttp.js file as below:
Now what i don't understand is in app.js when we create a callback function, we pass 2 parameters (err, posts) right?
How come we pass only one argument when we call callback function as below?
Also, in callback function declaration, we pass 2 parameters and in 'if' statement, we pass only one like if(err).
How this function knows that which one is err and which one is posts when only one parameter is passed.
I have a main easyhttp.js file as below:
function easyHTTP() {
this.http = new XMLHttpRequest();
}
easyHTTP.prototype.get = function (url, callback) {
this.http.open('GET', url, true);
self = this;
this.http.onload = function () {
if (self.http.status === 200) {
callback(null, self.http.responseText);
} else {
callback('Error: ' + self.http.status);
}
};
this.http.send();
}
And I execute it on the following app.js file.const http = new easyHTTP();
http.get('https://jsonplaceholder.typicode.com/posts',
(err, posts) => {
if (err) {
console.log(err);
} else {
console.log(posts);
}
})
Now what i don't understand is in app.js when we create a callback function, we pass 2 parameters (err, posts) right?
How come we pass only one argument when we call callback function as below?
callback('Error: ' + self.http.status);
Also, in callback function declaration, we pass 2 parameters and in 'if' statement, we pass only one like if(err).
How this function knows that which one is err and which one is posts when only one parameter is passed.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Julian for your detailed explanation!!!
You are welcome.