【发布时间】:2021-09-07 05:18:26
【问题描述】:
我对轴 GET 请求的循环有问题,我不明白为什么。
const [ state, setState ] = useState<any[]>([]);
ids.forEach((id) => {
getData(id)
.then((smth: Map<string, any>[]) => getNeededData(smth, id));
});
console.log(JSON.stringify(state));
和getData(getNeededData只是选择参数):
export const getData= async (id: string) => {
const response = await Axios.get(`/rest/${id}`)
.then((res: { data: any; }) => res.data);
return response;
};
我应该有 2 个响应(它是变量“ids”中的 2 个 id),但我有第一个、第二个、第一个、第二个、第一个,并且 this 在一个循环中。 为什么它一直这样工作? 我可以改变什么来解决这个问题?
【问题讨论】:
-
您希望这些请求串行执行还是并行执行?
-
最多5个请求,所以差别不大,但我很好奇,如何在串行和并行之间切换? :)
标签: reactjs typescript promise axios