我的代码:
const getData = async () => {
try {
let array = [];
axios.get(`https://swapi.dev/api/films/1/`)
.then(firstData=>{
Promise.all(
firstData.data["characters"].map(url=>{
axios.get(url)
.then(character=>{
array.push(character.data.name);
})
})
).then(result=>{
console.log("array:",array);
JSON.stringify(array);
})
})
} catch (err ) {
// errors
console.log(err,"connection error")
}
}
useEffect(() => {
getData()
}, []);
在记录阵列之前,您没有等待所有promise都得到解决,主要问题是您没有从map函数返回promise,您可以执行以下操作:
const getData = async () => {
try {
let array = [];
const firstData = await axios.get(`https://swapi.dev/api/films/1/`)
await Promise.all(
firstData.data["characters"].map(url=>{
return axios.get(url).then(character=>{
array.push(character.data.name);
})
})
).then(result=>{
console.log("array:",array);
JSON.stringify(array);
})
} catch (err ) {
// errors
console.log(err,"connection error")
}
}