1 回答

TA貢獻(xiàn)1712條經(jīng)驗 獲得超3個贊
將您的代碼更新為以下內(nèi)容:
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: [...]
},
]
}
}
*/
}
));
}
添加回答
舉報