在javascript中异步使用chunked数据 [英] Consuming chunked data asyncrhonously in javascript
问题描述
我有一个(GET)端点以块的形式发送数据( Transfer-Encoding:chunked
)。数据是JSON编码并逐行发送。
I have a (GET) endpoint that sends data in chunks (Transfer-Encoding: chunked
). The data is JSON encoded and sent line by line.
有没有办法在JavaScript中以异步方式使用此端点发送的数据(或使用一些JavaScript库)?
Is there a way to consume the data sent by this endpoint in an asynchronous manner in JavaScript (or using some JavaScript library)?
要清楚,我知道如何执行异步 GET
,但我想拥有 GET
请求不等待传输整个数据,而是在数据到达时逐行读取数据。例如,在执行时:
To be clear, I know how to perform an asynchronous GET
, but I would like to have the GET
request not waiting for the whole data to be transfered, but instead read the data line by line as it arrives. For instance, when doing:
curl http://localhost:8081/numbers
下面的行在它们可用时逐一显示(我所做的示例服务器在发送一行和第二行之间等待一秒钟)。
The lines below are shown one by one as they become available (the example server I made is waiting a second between sending a line and the second).
{"age":1,"name":"John"}
{"age":2,"name":"John"}
{"age":3,"name":"John"}
{"age":4,"name":"John"}
我想重现相同的行为 curl
展品,但在浏览器中。我不想让用户等到所有数据都可用才能显示任何内容。
I would like to reproduce the same behavior curl
exhibits, but in the browser. I don't want is leave the user wait till all the data becomes available in order to show anything.
推荐答案
感谢< a href =https://stackoverflow.com/users/388787/dan-d> Dan 和减少我能够使用获取API 。需要注意的是,这不适用于Internet Explorer,并且必须由用户在Firefox中启用:
Thanks to Dan and Redu I was able to put together an example that consumes data incrementally, using the Fetch API . The caveat is that this will not work on Internet Explorer, and it has to be enabled by the user in 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 ();
})
完整示例(带服务器)可用在我的沙箱中。我发现它说明了 XMLHttpRequest
的限制,将此版本与这个,它不使用 fetch
API。
The full example (with the server) is available at my sandbox. I find it illustrative of the limitations of XMLHttpRequest
to compare this version with the this one, which does not use the fetch
API.
这篇关于在javascript中异步使用chunked数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!