Shamoon
Shamoon

Reputation: 43531

With expressJS, does res and req pass through to functions?

I'm using CoffeeScript, just a heads up:

searchResults = (err, data)->
  res.write 'hello'
  console.log data
  console.log 'here'
  return


exports.search = (req, res) ->
  res.writeHead 200, {'Content-Type': 'application/json'}
  location = req.param 'location'
  item = req.param 'item'

  geoC = googlemaps.geocode 'someaddress', (err, data) ->
      latLng = JSON.stringify data.results[0].geometry.location

      myModule.search latLng, item, searchResults

      return
  return

The searchResults function doesn't know about res, so how can I return data to the browser?

Upvotes: 0

Views: 475

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

It's a pretty common scenario. One option is to define searchResults inside of exports.search, but then exports.search might get unwieldy.

It doesn't make sense for searchResults to be defined in such a way that it uses res when res isn't an argument. But you may be reluctant to have functions with several arguments, which can lead to repetitive code when you have several callbacks that need to access the same state. One good option is to use a single hash to store that state. In this case, your code might look something like

searchResults = (err, data, {res}) ->
  ...

exports.search = (req, res) ->
  res.writeHead 200, {'Content-Type': 'application/json'}
  location = req.param 'location'
  item = req.param 'item'
  state = {req, res, location, item}

  geoC = googlemaps.geocode 'someaddress', (err, data) ->
      state.latLng = JSON.stringify data.results[0].geometry.location
      myModule.search state, searchResults
      return
  return

Notice that myModule.search now only takes the state hash and a callback; it then passes the state hash as the third argument to that callback (searchResults), which pulls res out of the hash using the destructuring argument syntax.

Upvotes: 1

Raynos
Raynos

Reputation: 169421

A standard bind will do.

myModule.search latLng, item, searchResults.bind(null, res)

...

searchResults = (res, err, data)->
  res.write 'hello'
  console.log data
  console.log 'here'
  return

Upvotes: 1

Related Questions