后端响应巨量数据,如何优化性能?

  • WebSocket
  • 流式传输 fetch
  • 虚拟滚动 (渲染性能提升,一次性记载固定条数)
  • 分片滚动

fetch流式传输


async function streamData(url) {
  unction streamOutput(msg) {
  // 发送 POST 请求
  fetch('url', {
    method:"POST",
    body:JSON.stringify({ "content": msg}),
    timeout: 0,
    dataType:"text/event-stream",
    headers:{
      "Content-Type":"application/json"
    },
  }).then(response => {
    // 检查响应是否成功
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // 返回一个可读流
    return response.body;
  }).then(body => {
    disableLoading();
    const reader = body.getReader();
    // 读取数据流
    function read() {
      return reader.read().then(({ done, value }) => {
        // 检查是否读取完毕
        if (done) {
          console.log('已传输完毕');
          return;
        }
        // 处理每个数据块
        console.log('收到的数据:', value);
        // 继续读取下一个数据块
        read();
      });
    }
    // 开始读取数据流
    read();
  }).catch(error => {console.error('Fetch error:', error);});
}

你可能感兴趣的:(js,ts,javascript)