Fetch API 等待定义块大小的块

问题描述 投票:0回答:1

我想获取一个 URL 并按定义大小的块处理响应。我也不想在等待整个块可用时阻塞。 Fetch API 中有类似的功能吗?

示例如下:

const response = await fetch(url)
const reader = response.body.getReader()
const chunk = await reader.read(CHUNK_SIZE) 

javascript asynchronous fetch-api
1个回答
7
投票

fetch() 支持像流一样使用。请参阅此处MDN 参考。看来您需要一些 ReadableStream 的样板代码......

代码如下:

const workOnChunk = (chunk) => { console.log("do-work")};

// Fetch your stuff  
fetch(url)
// Retrieve its body as ReadableStream
.then(response => response.body)

// Boilerplate for the stream - refactor it out in a common utility.
.then(rs => {
  const reader = rs.getReader();

  return new ReadableStream({
    async start(controller) {
      while (true) {
        const { done, value } = await reader.read();

        // When no more data needs to be consumed, break the reading
        if (done) {
          break;
        }

        // Do your work: ¿¿ Checkout what value returns ¿¿
        workOnChunk(value)

        // Optionally append the value if you need the full blob later.
        controller.enqueue(value);
      }

      // Close the stream
      controller.close();
      reader.releaseLock();
    }
  })
})
// Create a new response out of the stream (can be avoided?)
.then(rs => new Response(rs))
// Create an object URL for the response
.then(response => response.blob())
.then(blob => { console.log("Do something with full blob") }
.catch(console.error)


注意:nodejs-fetch API 并不完全相同。如果您使用的是 Nodejs,请参阅 nodeje-fetch 的流支持

© www.soinside.com 2019 - 2024. All rights reserved.