2011-09-12 27 views
0

我使用CoffeeScript,剛擡起頭:使用expressJS,res和req是否通過函數?

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 

searchResults功能不知道res,所以我怎麼能數據返回到瀏覽器?

回答

1

這是一個很常見的情況。一種選擇是在exports.search內定義searchResults,但exports.search可能會變得笨重。

searchResults被定義爲res不是參數時,它使用res沒有意義。但是,您可能不願意使用多個參數的函數,當您有多個需要訪問相同狀態的回調函數時,這些函數會導致重複的代碼。一個不錯的選擇是使用單個散列來存儲該狀態。在這種情況下,你的代碼可能看起來像

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 

注意myModule.search現在只需要在state哈希和回調;然後它將state散列作爲第三個參數傳遞給該回調(searchResults),該參數使用解構參數語法將res拉出散列。

1

標準綁定將會執行。

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

... 

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