ReadableStreamDefaultController.enqueue() - Web APIs 编辑
The enqueue()
method of the ReadableStreamDefaultController
interface enqueues a given chunk in the associated stream.
Syntax
readableStreamDefaultController.enqueue(chunk);
Parameters
- chunk
- The chunk to enqueue.
Return value
undefined
.
Exceptions
- TypeError
- The source object is not a
ReadableStreamDefaultController
.
Examples
In the following simple example, a custom ReadableStream
is created using a constructor (see our Simple random stream example for the full code). The start()
function generates a random string of text every second and enqueues it into the stream — see controller.enqueue(string)
. A cancel()
function is also provided to stop the generation if ReadableStream.cancel()
is called for any reason.
When a button is pressed, the generation is stopped, the stream is closed using ReadableStreamDefaultController.close()
, and another function is run, which reads the data back out of the stream.
const stream = new ReadableStream({
start(controller) {
interval = setInterval(() => {
let string = randomChars();
// Add the string to the stream
controller.enqueue(string);
// show it on the screen
let listItem = document.createElement('li');
listItem.textContent = string;
list1.appendChild(listItem);
}, 1000);
button.addEventListener('click', function() {
clearInterval(interval);
fetchStream();
controller.close();
})
},
pull(controller) {
// We don't really need a pull in this example
},
cancel() {
// This is called if the reader cancels,
// so we should stop generating strings
clearInterval(interval);
}
});
Specifications
Specification | Status | Comment |
---|---|---|
Streams The definition of 'enqueue()' in that specification. | Living Standard | Initial definition. |
Browser compatibility
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论