javascript - CoffeeScript:请求返回看起来像是流的内容

标签 javascript stream coffeescript request

有一个函数来轮询 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/

相关文章:

javascript - XMLHttpRequest URL 格式错误 - 错误 405

c++ - 从读入内存的文件中提取数据

java - 'ZipException : invalid code lengths set' when streaming input file to Apache-POI

javascript - 这个方法调用是如何工作的?

javascript - 如何复制粘贴 Canvas 的旋转部分而不重叠或多个 Canvas ?

javascript - 如何通过jquery将url加载到windows中?

javascript - 带有 Node.js 的 Twilio MMS - 发送多个媒体文件

javascript - 使用正则表达式查看字符串是否仅包含该单词,而不包含在另一个单词中

architecture - 实时数据处理架构

javascript - 咕噜.js : Loading task causes TypeError: object is not a function