0

Mostly working with Java so when I came across this code:

document.querySelector('form').onsubmit = formSubmit

function formSubmit (submitEvent) {
  var name = document.querySelector('input').value
  request({
    uri: "http://example.com/upload",
    body: name,
    method: "POST"
  }, postResponse)
}

function postResponse (err, response, body) {
  var statusMessage = document.querySelector('.status')
  if (err) return statusMessage.value = err
  statusMessage.value = body
}

Question is why are we using postResponse in formSubmit when the function is postResponse (err, response, body). When we are using postResponse how does it know which parameters are err, response and body?

Thanks.

Anton Kim
  • 879
  • 13
  • 36

1 Answers1

2

postResponse is a variable. The value of that variable is a function.

Putting () after a variable containing a function will call that function.

Putting (something, something) after a variable containing a function will call the function and pass it some arguments.

This code isn't calling the function. It is passing it as an argument to request. Some other code may call it later.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. In formSubmit(), postResponse will be executed with which parameters? Where is it getting err, response, body from? – Anton Kim Jan 07 '17 at 20:25
  • "In formSubmit(), postResponse will be executed with which parameters?" — It won't. As I said: *It is passing it as an argument to request* – Quentin Jan 07 '17 at 20:37
  • "Where is it getting err, response, body from?" — Look at the source code to the `request` function to find that out. – Quentin Jan 07 '17 at 20:37