fetch获取流式数据并逐个打字效果

fetch获取流式数据并逐个打字效果

一、直接上代码

 async sendRequest(messageId, content, questionId, questionType, aiToken, innerIndex) {
      let that = this;
      const response = await fetch(
        `${
          process.env.VUE_APP_WEB_API
        }/urlf_rnd=${new Date().getTime()}&message_id=${messageId}&question_id=${messageId}&question_type=${questionType}&stream=true`,
        {
          method: 'GET',
          cache: 'no-cache',
          headers: {
            'Content-Type': 'text/event-stream',
            aiToken: aiToken,
          },
        }
      ).then(response => {
        //     function read() {
        //   return reader.read().then(({ done, value }) => {
        //     if (done) {
        //       console.log('Stream complete');
        //       return;
        //     }
        //     console.log(value);
        //     return read(); // 继续读取
        //   });
        // }
        // return read();

        const reader = response.body.getReader();
        let buffer = ''; // 用于累积数据块
        let resultWord = ''; //返回的答案
        function read() {
          reader
            .read()
            .then(({ done, value }) => {
              that.loading = false;
              that.scrollFlag = false;
              if (done) {
                // 尝试解析最后一个数据块(如果有的话)
                if (buffer) {
                  try {
                    const lastChunk = buffer.trim().replace(/^data:/, ''); // 移除可能的 'data:' 前缀并去除首尾空白
                    const json = JSON.parse(lastChunk);
                    // 处理最后一个JSON对象
                    console.log(json);
                  } catch (e) {
                    console.error('Error parsing last chunk:', e);
                  }
                }
                console.log('Stream complete');

                that.requestRecomme1(messageId, innerIndex);
                return;
              }
              // 将新读取的数据块添加到缓冲区中
              const chunk = new TextDecoder().decode(value);
              buffer += chunk;
              // 尝试按行分割数据块并处理
              const lines = buffer.split(/\r?\n/);
              let fullLines = lines.slice(0, -1); // 最后一行可能是不完整的,所以保留在缓冲区中
              buffer = lines.slice(-1)[0]; // 更新缓冲区为剩余的不完整行
              console.log(fullLines, 'fullLines');
              fullLines.forEach(line => {
                const jsonString = line.trim().replace(/^data:/, ''); // 移除 'data:' 前缀并去除首尾空白
                try {
                  if (line) {
                    const json = JSON.parse(jsonString);
                    // 处理每个JSON对象
                    console.log(json.data.content, json, 'json');
                    resultWord += json.data.content;
                    that.$set(that.messageList, innerIndex, {
                      type: 'right',
                      session_id: json.data.session_id,
                      message_id: json.data.message_id,
                      reply_id: json.data.reply_id,
                      message: resultWord,
                      source: [],
                      sourceEdit: [],
                      question: [],
                    });
                    that.receiveMsg = that.messageList[innerIndex];
                    that.chcekScroll();
                    that.executeScroll(!that.scrollFlag);
                  }
                } catch (e) {
                  console.error('Error parsing JSON:', e, 'in line:', line);
                }
              });

              // 递归调用 read 方法以继续读取流
              read();
            })
            .catch(error => console.error('Error reading stream:', error));
        }
        read();
      });
    },
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值