【问题标题】:Fetch API await chunk of defined chunk size获取 API 等待已定义块大小的块
【发布时间】:2023-03-12 01:35:02
【问题描述】:

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

示例如下:

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

【问题讨论】:

    标签: javascript asynchronous fetch fetch-api


    【解决方案1】:

    fetch() 支持像流一样被使用。见MDN reference here。看来您需要一些用于 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's stream support

    【讨论】:

    • 在您的示例中,await reader.read() 将读取任何可用字节?我想等到至少有CHUNK_SIZE 字节可用。
    • 它将为您提供任何可用的东西。您可以check the length of chunk 并决定对其进行处理或将其放入列表中,直到它达到大小为止。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2011-11-06
    相关资源
    最近更新 更多