有一个函数来轮询 SOAP 端点
someFunction = (task={}, callback)->
req = {}
req.body = buildEnvelope(task) # this works correctly
result = {}
request.post(
{url: <<wsdl string>>, body: req.body, headers: {"Content-Type": "text/xml"}},
(error, response, body) ->
if not error and response.statusCode is 200
result = buildHash(body) # this builds a hash from the result, correctly
return result
)
所有内部函数都按预期工作,但是当我尝试执行诸如 console.log(someFunction(hash, ()->)
之类的操作时,我得到了奇怪的内容:
{ domain: null,
_events: { error: [Function], complete: [Function], pipe: [Function] },
_maxListeners: 10,
readable: true,
writable: true,
body: <Buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f 64 69 6e 67 3d 22 55 54 46 2d 38 22 3f 3e 20 3c 53 4f 41 50 2d 45 4e 56 3a 45 6e ...>,
headers:
{ 'Content-Type': 'text/xml',...}
它看起来像是从请求
返回的某种风格的流对象。我猜测这是因为我将 return
语句放在 request.post()
调用的中间,但是如果我将它放在该调用之外,它返回一个空哈希,因为返回发生在 POST 操作发生之前。
获取我期望运行 someFunction()
后由函数返回的哈希值的最佳方法是什么?
最佳答案
该返回值是 request.post
返回的值。如果 CoffeeScript 函数没有显式的 return 语句,则它返回最后执行的语句的值;在您的情况下,这将是 request.post
调用。
没有什么可能关心你的 request.post
回调返回什么,所以你的:
return result
毫无意义。如果您想从异步回调中获取某些内容返回给外界,那么您需要使用 callback
参数:
someFunction = (task={}, callback)->
#...
request.post(
{url: <<wsdl string>>, body: req.body, headers: {"Content-Type": "text/xml"}},
(error, response, body) ->
if not error and response.statusCode is 200
callback(buildHash(body)) # <------------------
)
someFunction({...}, (hash) ->
# Do something interesting with `hash` in here...
)
当然,callback
的真正调用约定取决于您具体需要返回的内容。
关于javascript - CoffeeScript:请求返回看起来像是流的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25318127/