开发者

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

开发者 https://www.devze.com 2023-04-04 21:01 出处:网络
I\'m using CoffeeScript, just a heads up: searchResults = (err, data)-> res.write \'hello\' console.log data

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, searchRes开发者_Go百科ults

      return
  return

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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消