首页 > 解决方案 > 并行运行 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?

标签: javascriptarraysreactjsajaxtypescript

解决方案


推荐阅读