在JavaScript中异步使用分块数据

Dam*_*les 3 javascript asynchronous http http-streaming

我有一个(GET)端点,它以块(Transfer-Encoding: chunked)的形式发送数据。数据经过JSON编码并逐行发送。

有没有办法在JavaScript中(或使用某些JavaScript库)以异步方式使用此终结点发送的数据?

明确地说,我知道如何执行异步操作GET,但是我希望GET请求不等待整个数据传输,而是在到达时逐行读取数据。例如,在执行以下操作时:

curl  http://localhost:8081/numbers
Run Code Online (Sandbox Code Playgroud)

当下面的行可用时,将逐行显示(我制作的示例服务器在发送第二行之前等待一秒钟)。

{"age":1,"name":"John"}
{"age":2,"name":"John"}
{"age":3,"name":"John"}
{"age":4,"name":"John"}
Run Code Online (Sandbox Code Playgroud)

我想curl在浏览器中重现相同的行为。我不想让用户等到所有数据变得可用以显示任何内容。

Dam*_*les 6

多亏了DanRedu,我才能够使用Fetch API 编写一个示例,逐步使用数据。需要注意的是,这在Internet Explorer上将不起作用,并且必须由Firefox用户启用:

   /** This works on Edge, Chrome, and Firefox (from version 57). To use this example
    navigate to about:config and change

    - dom.streams.enabled preference to true
    - javascript.options.streams to true


    See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
*/

fetch('http://localhost:8081/numbers').then(function(response) {

  console.log(response);

  const reader = response.body.getReader();

  function go() {
    reader.read().then(function(result) {
      if (!result.done) {
        var num = JSON.parse(
          new TextDecoder("utf-8").decode(result.value)
        );
        console.log(
          "Got number " + num.intVal
        );        
        go ();
      }
    })
  }

  go ();
})
Run Code Online (Sandbox Code Playgroud)

完整的示例(带有服务器)在我的沙箱中可用。我觉得这说明了限制,XMLHttpRequest这个版本与比较这一个,不使用的fetchAPI。