2012-02-22 60 views
2

返回值我在CoffeeScript的以下功能:如何從一個異步調用

newEdge: (fromVertexID, toVertexID) -> 
    edgeID = this.NOID 
    @client.methodCall('ubigraph.new_edge', [fromVertexID, toVertexID], (error, value) -> 
     if(error) 
      console.log('ubigraph.new_edge error: ' + error) 
     edgeID = value 
    ) 
    edgeID 

其中@ client.methodCall指XMLRPC庫。 我的問題是如何返回值作爲edgeID。我是否使用回調?

如果是這樣,那麼回調看起來應該是這樣的:?

# callback is passed the following parameters: 
# 1. error - an error, if one occurs 
# 2. edgeID - the value of the returned edge id 
newEdge: (fromVertexID, toVertexID, callback) -> 
    @client.methodCall('ubigraph.new_edge', [fromVertexID, toVertexID], (error, value) -> 
     if(error) 
      console.log('ubigraph.new_edge error: ' + error) 
     edgeID = value 
     callback(error, value) 
    ) 

回答

3

是的,回調是異步調用通常的解決辦法,有時你不得不調用回調函數調用回調回調,回調一路下滑。我可能會做一點點不同,但:

newEdge: (fromVertexID, toVertexID, on_success = ->, on_error = ->) -> 
    @client.methodCall('ubigraph.new_edge', [fromVertexID, toVertexID], (error, edge_id) -> 
     if(error) 
      console.log('ubigraph.new_edge error: ' + error) 
      on_error(error) 
     else 
      on_success(edge_id) 
    ) 

的主要區別是,該礦擁有獨立的成功和錯誤回調,使主叫方可以單獨處理這些條件下,不同的條件是相互獨立的回調是一種常見的方法,使它應該是大多數人熟悉的。我還添加了默認的無操作回調函數,以便回調函數是可選的,但主方法體可以假裝它們總是被提供。

如果你不喜歡使用四個參數,那麼你可以使用「命名」參數的回調:

newEdge: (fromVertexID, toVertexID, callbacks = { }) -> 
    @client.methodCall('ubigraph.new_edge', [fromVertexID, toVertexID], (error, edge_id) -> 
     if(error) 
      console.log('ubigraph.new_edge error: ' + error) 
      callbacks.error?(error) 
     else 
      callbacks.success?(edge_id) 
    ) 

使用對象/散列的回調,您可以使用existential operator而不是無操作的使回調可選。


Aaron Dufour指出,一個回調是Node.js的通常模式,使你原來的做法將是一個更適合的node.js:

newEdge: (fromVertexID, toVertexID, callback = ->) -> 
    @client.methodCall('ubigraph.new_edge', [fromVertexID, toVertexID], (error, edge_id) -> 
     if(error) 
      console.log('ubigraph.new_edge error: ' + error) 
     callback(error, edge_id) 
    ) 
+0

即使有一個回調,的用戶函數可以決定在每種情況下做什麼,但基本上,您的答案是:回調是做到這一點的方法。是我一直在尋找的人。謝謝 – lowerkey 2012-02-22 20:03:11

+0

@lowerkey:真的夠了,但單獨的回調似乎是通常的方法; jQuery至少對成功和錯誤條件使用單獨的回調函數,所以大多數人都會很熟悉它。我已經(嘗試)澄清這一點。 – 2012-02-22 20:18:29

+1

大多數node.js庫都使用單個回調,並將錯誤作爲第一個參數,這使得它們都可以相互無縫地彼此通信。我會建議通過單獨的回調。 – 2012-02-22 23:52:44