wx.request({
url,
method: 'POST',
header: {
Accept: 'text/event-stream',
Authorization: 'Bearer ' + tokens.get(),
traceId: random(),
...header,
},
enableChunked: true,
data: params,
success: () => {
success();
},
fail: (err) => {
console.log('流接口错误', err);
fail();
},
complete: () => {
console.log('完成');
complete();
},
});
reqTask.onChunkReceived((res) => {
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
const originStr = new TextEncoding.TextDecoder('utf-8').decode(uint8Array);
console.log('原始数据', originStr);
const formatStr = 'data:';
const formatStrLen = formatStr.length;
const parsedData = originStr
.split('\n')
.filter((txt) => txt.trim() !== '')
.map((txt) => {
const str = txt.startsWith(formatStr) ? txt.slice(formatStrLen) : txt;
try {
return str.trim() ? JSON.parse(str) : null;
} catch (e) {
console.error('JSON.parse error', e, str);
return null;
}
})
.filter((data) => data !== null); // 过滤掉解析错误的项
const sortedData = [...parsedData].sort((a, b) => a.data.n - b.data.n); // 按 n 值排序
sortedData.forEach((data) => {
receivedData(data, reqTask);
});
})
返回的数据中有个 n 字段,是实际的数据顺序,现在完全是乱的。
而且后端是是一条一条给的数据,onChunkReceived 却是一段一段接受的,是为什么?