基础
参考
https://blog.csdn.net/qq_52855464/article/details/125376557
简单来说
Promise.all是处理接口返回方法异步的,能够使得接口的获取顺序得到控制,不会出现数据为空的情况
使用
先执行jianshigetGroups->groupIds-> const promises2 = groupIds.map(id => togetMoshi(id));-> const transformedData (处理最终的的数据)
等待一个方法
代码如下
jianshigetGroups().then((response) => {const groupIds = response.data.map(item => item.id);const promises = groupIds.map(id => getGroupName(id));const moshiids = null;Promise.all(groupIds.map(id => togetMoshi(id))).then(results => {moshiids.value = resultsconsole.log(results);});const promises2 = groupIds.map(id => togetMoshi(id));console.log(promises2)Promise.all(promises).then(names => {const transformedData = response.data.map((item, index) => ({value: item.id,label: names[index].name,id: item.id,name: names[index].name,cumulatedPowerIn: names[index].cumulatedPowerIn,cumulatedPowerOut: names[index].cumulatedPowerOut,isOnline: names[index].isOnline,}));console.log(transformedData);groups.value = transformedData;}).catch(error => {console.log(error);});});const getGroupName = (id) => {return jianshigetGroupDetail(id).then((response) => {return response.data;});};const togetMoshi = (id) => {return getMoshi(id).then((response) => {return response.data;});};
等待两个
与等待一个不同的是等待一个是
Promise.all(promises)
.then(names => {
另一个是
Promise.all([Promise.all(promises), Promise.all(promises2)])
.then(names => {
第二种写法需要定义两个数组用于存放不同的值 也可以用数组下标来区分
jianshigetGroups().then((response) => {const groupIds = response.data.map(item => item.id);const promises = groupIds.map(id => getGroupName(id));const promises2 = groupIds.map(id => togetMoshi(id));Promise.all([Promise.all(promises), Promise.all(promises2)]).then(names => {const groupNames = names[0];const moshiData = names[1];const transformedData = response.data.map((item, index) => ({value: item.id,label: groupNames[index].name,id: item.id,name: groupNames[index].name,cumulatedPowerIn: groupNames[index].cumulatedPowerIn,cumulatedPowerOut: groupNames[index].cumulatedPowerOut,isOnline: groupNames[index].isOnline,moshiid:moshiData[index].mode}));console.log(transformedData);groups.value = transformedData;}).catch(error => {console.log(error);});
});const getGroupName = (id) => {return jianshigetGroupDetail(id).then((response) => {return response.data;});
};const togetMoshi = (id) => {return getMoshi(id).then((response) => {return response.data;});
};