api调用流程图
Using streams we can receive a resource from the network, or from other sources, and process it as soon as the first bit arrives.
使用流,我们可以从网络或其他来源接收资源,并在第一位到达时对其进行处理。
Instead of waiting for the resource to completely download before using it, we can immediately work with it.
无需等待资源完全下载再使用,我们可以立即使用它。
The first example that comes to mind is loading a YouTube video - you don’t have to fully load it before you can start watching it.
我想到的第一个示例是加载YouTube视频-您无需完全加载它即可开始观看。
Or live streaming, where you don’t even know when the content will end.
或实时流式传输,甚至不知道内容何时结束。
The content does not even have to end. It could be generated indefinitely.
内容甚至不必结束。 它可以无限期生成。
The Streams API allows us to work with this kind of content.
Streams API允许我们处理此类内容。
We have 2 different streaming modes: reading from a stream, and writing to a stream.
我们有2种不同的流传输模式:从流读取和写入流。
Readable streams are available in all modern browsers except Internet Explorer.
除Internet Explorer之外,所有现代浏览器均提供可读流。
Writable streams are not available on Firefox and Internet Explorer.
可写流在Firefox和Internet Explorer上不可用。
As always, check caniuse.com for the most up-to-date information on this matter.
与往常一样,请访问caniuse.com ,以获取有关此问题的最新信息。
Let’s start with readable streams
让我们从可读流开始
We have 3 classes of objects when it comes to readable streams:
关于可读流,我们有3类对象:
ReadableStream
ReadableStream
ReadableStreamDefaultReader
ReadableStreamDefaultReader
ReadableStreamDefaultController
ReadableStreamDefaultController
We can consume streams using a ReadableStream object.
我们可以使用ReadableStream对象使用流。
Here is the first example of a readable stream. The Fetch API allows to get a resource from the network and make it available as a stream:
这是可读流的第一个示例。 Fetch API允许从网络获取资源并将其作为流使用:
const stream = fetch('/resource')
.then(response => response.body)
The body
property of the fetch response is a ReadableStream
object instance. This is our readable stream.
提取响应的body
属性是ReadableStream
对象实例。 这是我们可读的流。
Calling getReader()
on a ReadableStream
object returns a ReadableStreamDefaultReader
object, the reader. We can get it this way:
在ReadableStream
对象上调用getReader()
返回一个ReadableStreamDefaultReader
对象,即阅读器。 我们可以这样获得:
const reader = fetch('/resource').then(response => response.body.getReader())
We read data in chunks, where a chunk is a byte or a typed array. Chunks are enqueued in the stream, and we read them one chunk at a time.
我们分块读取数据,其中块是字节或类型数组。 将大块放入流中,我们一次读取一个大块。
A single stream can contain different kind of chunks.
单个流可以包含不同种类的块。
Once we have a ReadableStreamDefaultReader
object we can access the data using the read()
method.
一旦有了ReadableStreamDefaultReader
对象,就可以使用read()
方法访问数据。
As soon as a reader is created, the stream is locked and no other reader can get chunks from it, until we call releaseLock()
on it.
创建读取器后,流就被锁定,其他读取器无法从中获取任何块,直到我们对其调用releaseLock()
为止。
You