使用Promise.all后Axios返回含单个对象的嵌套数组问题
解决Axios批量GET请求返回嵌套数组问题
我需要通过Axios在map函数中批量执行GET请求,编写了如下函数接收ID数组,用Promise.all处理异步请求,但返回结果中每个对象都被嵌套在数组里,结构不符合预期。
原函数代码:
// Get imaged exercices export const getImagedExercices = async array => { let getIds = async element => { let array = await axios.get(`http://localhost:3000/api/get-exercice-by-id/${element}`); let data = await array.data; return data; } try { const arrayEx = array.map(item => item.exerciceId); let mappedResult = await Promise.all(arrayEx.map(async element => await getIds(element))); return mappedResult; } catch (error) { console.log(error); return error; } }
当前返回的嵌套数组结构:
[ [ { id: 'clcj22d650002sbdkmmobh33l', bodyPart: 'waist', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/0001.gif', name: '3/4 sit-up', target: 'abs' } ], [ { id: 'clcj22d650002sbdkmmobh33l', bodyPart: 'waist', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/0001.gif', name: '3/4 sit-up', target: 'abs' } ], [ { id: 'clcj22d650007sbdk9ncyidv1', bodyPart: 'upper legs', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/1512.gif', name: 'all fours squad stretch', target: 'quads' } ] ]
问题分析与解决方案
问题根源是后端接口/api/get-exercice-by-id/${element}返回的是数组格式(即使单个数据也用数组包裹),所以每个getIds函数返回的是数组,最终导致Promise.all的结果是数组嵌套数组。
修正方法很简单,在getIds函数中返回数组的第一个元素即可,同时可以简化不必要的await操作:
// Get imaged exercices export const getImagedExercices = async array => { let getIds = async element => { const response = await axios.get(`http://localhost:3000/api/get-exercice-by-id/${element}`); // 取返回数组的第一个元素,解除嵌套 return response.data[0]; } try { const arrayEx = array.map(item => item.exerciceId); // 简化map中的async逻辑,直接返回getIds返回的Promise const mappedResult = await Promise.all(arrayEx.map(getIds)); return mappedResult; } catch (error) { console.log(error); return error; } }
修正后返回的结构会变成预期的对象数组:
[ { id: 'clcj22d650002sbdkmmobh33l', bodyPart: 'waist', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/0001.gif', name: '3/4 sit-up', target: 'abs' }, { id: 'clcj22d650002sbdkmmobh33l', bodyPart: 'waist', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/0001.gif', name: '3/4 sit-up', target: 'abs' }, { id: 'clcj22d650007sbdk9ncyidv1', bodyPart: 'upper legs', equipment: 'body weight', gifUrl: 'http://d205bpvrqc9yn1.cloudfront.net/1512.gif', name: 'all fours squad stretch', target: 'quads' } ]
内容的提问来源于stack exchange,提问作者daniel sas
相关产品推荐
相关产品推荐

