javascript - 并行运行 2 级深度的 Promise 数组 React Typescript
问题描述
我希望你们都做得很好。我正在开发一个反应和打字稿网站。我有 2 个数组,我正在循环并将请求发送到后端并获取图像。大约,第一个数组有7
元素,第二个6
意味着至少 42 个请求。我能够在第二个数组中并行运行请求,但是我需要外部数组的帮助。这是我的代码:
export default function TestResults() {
const { search } = useLocation();
const { id: testId } = useParams<Params>();
const [screenshots, setScreenshots] = useState<AxiosResponse<ArrayBuffer>[][]>([]);
const queryParams = new URLSearchParams(search);
const projectId = queryParams.get('projectId');
const recentTestId = queryParams.get('recentTestId');
const scripts = queryParams.get('scripts')?.split(',');
useEffect(() => {
(async () => {
// REAL STUFF STARTS HERE: "resolutions" is "array1"
const screenshotPromises = resolutions!?.map(async (res, i: number) => {
const screenshotsByResolution = [];
// Array 2
for (let i = 0; i < scripts!?.length; i++) {
const prevImage: AxiosResponse<ArrayBuffer> = await axios.get(
`${process.env.REACT_APP_SERVER_URL}/api/tests/${projectId}/${testId}/images?resolution=${res}&resolutionNumber=${
i + 1
}`,
{ responseType: 'arraybuffer' }
);
const diffImage: AxiosResponse<ArrayBuffer> = await axios.get(
`${
process.env.REACT_APP_SERVER_URL
}/api/tests/${projectId}/${testId}/image-diff?resolution=${res}&resolutionNumber=${
i + 1
}&recentTestId=${recentTestId}`,
{ responseType: 'arraybuffer' }
);
screenshotsByResolution.push(prevImage, diffImage);
}
// [[prev, diff]]
console.log(screenshotsByResolution);
return screenshotsByResolution;
});
console.log(await Promise.all(screenshotPromises));
// @ts-ignore
setScreenshots(await Promise.all(screenshotPromises));
})();
// @ts-ignore
}, []);
}
Since the route does a lot of image manipulation, each request takes 4-5 seconds. And 2-3 mins of load time is not good UX.
As I mentioned earlier, the code in array1 i.e. `resolutions` array is being parallely executed but code in the `for` loop is not. I'd like to do these both parallely. If there is no solution to this, what would be the best approach?
解决方案
推荐阅读
- r - 使用应用族函数通过对多个其他列进行操作来创建多个数据框列
- python - Combining checks at the beginning of a method
- python - Paramiko SSH 连接到 Windows 主机。“VBoxManage.exe guestcontrol run”命令的空标准输出
- sharepoint - 如何连接 Sharepoint 中的两个字段?
- angular - Angular 2 在 URL 中使用带有基于路径的参数的 routerLinkActive
- c++ - Printing Integer Contents of a Vector as a String are Leading to Segmentation Fault
- lotus - 如何在 Lotus Notes 中创建一个按钮以查看收件箱中的最新电子邮件?
- maven - How to find a detailed document about what is Liberty Maven Plugin?
- akka.net - 无法在 Akka.Net 集群中创建节点级本地参与者
- reactjs - Redux-Observable - Cancel next request if it has same parameters with current one, but let it run when they are different