我正在尝试使用 axios.all 进行多个 pararell api 调用(其中很多),我想同时向响应添加新属性。我想将映射的数组值添加为“newProperty”,以便接收到的对象将具有该额外属性
const url='https://jsonplaceholder.typicode.com/posts/'
const arr=[1,2]
const fn = async () => {
const obj = (await axios.all(arr.map(el=>axios(url+el)))).map((item)=>item.data)
console.log(obj)
}
fn()
{
**"newProperty"**: 1,
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat",
"body": "quia et suscipit\nsuscipit recusandae consequuntur"
}
const url = 'https://jsonplaceholder.typicode.com/posts/'
const arr = [1, 2]
const urls = arr.map(postId => url + postId);
const fn1 = async () => {
const objs = await axios.all(urls.map((endpoint) => axios(endpoint)));
const datas = objs.map(obj => obj.data);
const transformedDatas = datas.map(data => { data.property = "value"; return data });
console.log(transformedDatas);
return transformedDatas;
}
(async () => {
await fn1();
})();
只需在您的 objs.map 中添加转换器代码,提取每个响应的数据组件并添加您要添加的属性 fn1 也是一个承诺,您需要等待它才能完成。