尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

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

fetch获取流式数据并逐个打字效果 fetch获取流式数据并逐个打字效果一、直接上代码一、直接上代码asyncsendRequest(messageId,content,questionId,questionType,aiToken,innerIndex){letthatthis;constresponseawaitfetch(${process.env.VUE_APP_WEB_API}/urlf_rnd${newDate().getTime()}message_id${messageId}question_id${messageId}question_type${questionType}streamtrue,{method:GET,cache:no-cache,headers:{Content-Type:application/json,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();constreaderresponse.body.getReader();letbuffer;// 用于累积数据块letresultWord;//返回的答案functionread(){reader.read().then(({done,value}){that.loadingfalse;that.scrollFlagfalse;if(done){// 尝试解析最后一个数据块如果有的话if(buffer){try{constlastChunkbuffer.trim().replace(/^data:/,);// 移除可能的 data: 前缀并去除首尾空白constjsonJSON.parse(lastChunk);// 处理最后一个JSON对象console.log(json);}catch(e){console.error(Error parsing last chunk:,e);}}console.log(Stream complete);that.requestRecomme1(messageId,innerIndex);return;}// 将新读取的数据块添加到缓冲区中constchunknewTextDecoder().decode(value);bufferchunk;// 尝试按行分割数据块并处理constlinesbuffer.split(/\r?\n/);letfullLineslines.slice(0,-1);// 最后一行可能是不完整的所以保留在缓冲区中bufferlines.slice(-1)[0];// 更新缓冲区为剩余的不完整行console.log(fullLines,fullLines);fullLines.forEach(line{constjsonStringline.trim().replace(/^data:/,);// 移除 data: 前缀并去除首尾空白try{if(line){constjsonJSON.parse(jsonString);// 处理每个JSON对象console.log(json.data.content,json,json);resultWordjson.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.receiveMsgthat.messageList[innerIndex];that.chcekScroll();that.executeScroll(!that.scrollFlag);}}catch(e){console.error(Error parsing JSON:,e,in line:,line);}});// 递归调用 read 方法以继续读取流read();}).catch(errorconsole.error(Error reading stream:,error));}read();});},
返回列表