Link to home
Start Free TrialLog in
Avatar of Isabell
Isabell

asked on

number of parameters in callback

Hi,

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();
}

Open in new window

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);
    }
  })

Open in new window


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);

Open in new window


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.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

User generated image
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Isabell
Isabell

ASKER

Thanks Julian for your detailed explanation!!!
You are welcome.