1 回答
TA贡献1712条经验 获得超3个赞
将您的代码更新为以下内容:
function fetchData(){
let urls = [
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'offline'
},
{
url: 'http://127.0.0.1:8000/api/offlineUserData',
type: 'offline'
},
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'online'
},
];
let requests = urls.map(item => fetch(item.url).then(response => response.json()));
const resultData = { offline: [], online: [] };
Promise.all(requests)
.then(datas => {
datas.forEach(
(data, i) => {
const url = urls[i];
if (url.type === 'offline')
resultData.offine.push({...url, data});
if (url.type === 'online')
resultData.online.push({...url, data});
});
console.log({resultData});
/*
{
resultData: {
offline: [
{
url: 'http://127.0.0.1:8000/api/oflineUserData',
type: 'offline',
data: [...]
},
{
url: 'http://127.0.0.1:8000/api/offlineUserData',
type: 'offline',
data: [...]
},
],
online: [
{
url: 'http://127.0.0.1:8000/api/onlineUserData',
type: 'online',
data: [...]
},
]
}
}
*/
}
));
}
添加回答
举报