To stream text from an API using the fetch method in JavaScript, you can use the ReadableStream API.

Here's an example code snippet:

fetch('https://api.example.com/text')
  .then(response => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        function push() {
          reader.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            controller.enqueue(value);
            push();
          });
        }
        push();
      }
    });
  })
  .then(stream => {
    const reader = new Response(stream).body.getReader();
    function read() {
      reader.read().then(({ done, value }) => {
        if (done) {
          console.log('Stream complete');
          return;
        }
        console.log(value);
        read();
      });
    }
    read();
  })
  .catch(error => {
    console.error(error);
  });

This code fetches a text stream from an API and reads the data as it arrives, logging it to the console. Note that the ReadableStream API is not supported in all browsers, so you may need to use a polyfill or fallback method if you need to support older browsers.

js stream text from api using fetch

原文地址: http://www.cveoy.top/t/topic/bbYx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录