uniapp h5页面 流式数据前端处理

const getResponse = async (content) => {
	try {
		const url = '后台地址';
		const response = await fetch(url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(content)
		});

		if (!response.ok) {
			throw new Error(`请求失败: ${response.status} ${response.statusText}`);
		}

		// 创建AI消息(初始为空)
		const aiMessageIndex = messages.length;
		isLoading.value = false;
		const reader = response.body.getReader();
		const decoder = new TextDecoder('utf-8');
		let buffer = '';
		let lastUpdateTime = 0;
		const UPDATE_INTERVAL = 100; // 更新间隔100ms避免频繁渲染
		const processChunk = (chunk) => {
			buffer += chunk;
			// 处理可能的多条数据(以"data: "开头)
			while (buffer.includes('data: ')) {
				const dataStart = buffer.indexOf('data: ');
				const dataEnd = buffer.indexOf('\n', dataStart);

				if (dataEnd === -1) break; // 不完整的数据,等待更多

				const dataLine = buffer.substring(dataStart + 6, dataEnd).trim();
				buffer = buffer.substring(dataEnd + 1);

				if (!dataLine) continue;

				try {
					const parsedData = JSON.parse(dataLine);
					if (parsedData.answer) {
						// 累积回答内容
						messages[aiMessageIndex].content += parsedData.answer;

						// 节流更新UI
						const now = Date.now();
						if (now - lastUpdateTime > UPDATE_INTERVAL) {
							scrollToBottom();
							lastUpdateTime = now;
						}
					}

					// 检查是否结束
					if (parsedData.flag === 'end') {
						scrollToBottom(); // 确保最后滚动到底部
						return true; // 结束标志
					}
				} catch (e) {
					console.error('解析JSON失败:', e);
				}
			}
			return false;
		};

		while (true) {
			const { done, value } = await reader.read();
			if (done) break;

			const chunk = decoder.decode(value, { stream: true });
			const shouldBreak = processChunk(chunk);
			if (shouldBreak) break;
		}

		// 处理缓冲区剩余数据
		if (buffer.trim()) {
			processChunk('');
		}
	} catch (error) {
		console.error('请求异常:', error);
		err.value = true;

		// 更新最后一条消息显示错误
		if (messages.length > 0 && messages[messages.length - 1].sender === 'ai') {
			messages[messages.length - 1].content = '服务响应异常,请稍后重试';
		} else {
			addMessage('ai', '服务响应异常,请稍后重试', '');
		}
	} finally {
		scrollToBottom(); // 最终确保滚动到底部
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值