未等待解决的异步调用循环



我正在尝试使用Pokeapi+Rreact Redux+TS 构建一个简单的口袋妖怪应用程序

对于那些熟悉这个API的人来说,对pokemon列表的基本调用返回一个带有pokemon名称的对象和一个带有端点的URL,以获得详细信息

我需要同时选择两个电话(列表+每个口袋妖怪的详细信息(。正在发生的事情是(显然(";列表";调用解析正常,但不等待详细调用来解决

此处编码:

async function getDetailedInfo(id: number) {
return  await 
axios.get(`https://pokeapi.co/api/v2/pokemon/${id}`);
}
export const morePokemon = (url: string) => async (dispatch: 
Function) => {
try {
const response = await axios.get(url); //Always resolves properly

const newPokemon: stateInterface['pokemon'] = 
response.data.results.map(
(element: { name: string; url: string }) => ({
name: element.name,
id: element.url.split('/')[6],
inTeam: false,
details: {}
})
);
newPokemon.forEach( async (pok, i)=>  {
newPokemon[i].details =  await getDetailedInfo(pok.id)
console.log(newPokemon[i].details) // REQUIRED DATA LOGED HERE
})

console.log(newPokemon) // REQUIRED DATA LOGED AS WELL
dispatch(nextPokemon(response.data.next));
return dispatch(morePokemonSuccess(newPokemon));
} catch (err) {
return err;
} 
};

但是,在组件中:

function PokemonList({
state,
dispatch,
}: {
state: stateInterface;
dispatch: Function;
}): JSX.Element {
useEffect(() => {
dispatch(morePokemon(state.next));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch]);
const list = state?.pokemon?.map((element: any) => {
console.log(element); // ******** //
return (
<div className="list__item" key={element.id}>
......

如果我在state.pokemon.map函数内控制台日志";元素";我可以看到;细节";属性,其中包含每个pokemon的详细信息,但如果我在同一点console.log";element.detail";,它返回一个空对象。

使用Redux调试工具,我可以看到详细信息是空的,这是异步问题,但我如何才能记录"元素";并看到";细节";属性用所需的数据来实现;elements.details";,显示一个空对象?与登录";更多口袋妖怪";作用这种情况只发生在";getDetailedInfo"功能

这简直把我逼疯了。

使用ES2018,您可以使用循环顺序执行API调用。

for await (const [i, pok] of newPokemon.entries()) {
newPokemon[i].details =  await getDetailedInfo(pok.id)
}

最新更新