如何从asynchronous调用中返回值

我在coffeescript中有以下function:

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?

如果是这样,callback应该是这样的:?

 # 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) ) 

是的,callback是asynchronous调用的通常解决scheme,有时你有callback调用callback,callback,callback。 我可能会做一些不同的事情:

 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) ) 

主要区别在于我的成功和错误callback是分开的,这样调用者可以单独处理这些条件,对于不同的条件单独callback是一个常用的方法,所以大多数人都应该很熟悉。 我还添加了默认的无操作callback,以便callback是可选的,但主方法体可以假装他们总是提供。

如果你不喜欢使用四个参数,那么你可以使用“命名”参数的callback:

 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) ) 

对callback使用对象/散列可以使用存在操作符而不是无操作来使callback成为可选项。


Aaron Dufour指出,单个callback是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) )