【问题标题】:Parallel/Sequential Calling of API in React and Redux and AxiosReact 和 Redux 和 Axios 中 API 的并行/顺序调用
【发布时间】:2022-08-18 18:22:48
【问题描述】:

我需要确定是否需要按顺序或并行上传照片(调用上传 API)。

顺序意味着当您上传图片时(调用上传API),您等待第一个被解析然后显示图像,然后再调用下一个上传API。

并行意味着当您上传图像时,您首先显示已解析的任何图像。因此,您可以同时显示图像,因为这里可以解决多重响应。

我想有一个条件是顺序还是并行 uploadPhotos 行动。 条件是当它包含相同的文件名时使用顺序,例如如果您上传aa_11-01.jpg,然后您上传aa_11-02.jpg,否则使用并行。

平行

export const uploadPhotos =
  ({ photos, size, controller }) =>
  async (dispatch) => {
    photos.forEach(async (photo, index) => {
      const formData = new FormData();
      formData.append(photo?.imageFileName, photo?.imageFile)

      dispatch({ type: constants.UPLOAD_PHOTOS_START, size });
      try {
        const response = await axios.post(
          `${API_URL}/photos/upload`,
          formData,
          {
            onUploadProgress({ loaded, total }) {
              dispatch(setUploadProgress({ id: index, loaded, total }));
            },
            signal: controller.signal,
          }
        );

        dispatch({
          type: constants.UPLOAD_PHOTOS_SUCCESS,
          payload: response.data,
        });
      } catch (error) {
        dispatch({
          type: constants.UPLOAD_PHOTOS_FAILURE,
          payload: error,
        });
      }
    });
  };

顺序的

export const uploadPhotos =
      ({ photos, size, controller }) =>
      async (dispatch) => {
        for (const [index, photo] of photos.entries()) {
          const formData = new FormData();
            formData.append(photo?.imageFileName, photo?.imageFile)
    
          dispatch({ type: constants.UPLOAD_PHOTOS_START, size });
          try {
            const response = await axios.post(
              `${API_URL}/photos/upload`,
              formData,
              {
                onUploadProgress({ loaded, total }) {
                  dispatch(setUploadProgress({ id: index, loaded, total }));
                },
                signal: controller.signal,
              }
            );
    
            dispatch({
              type: constants.UPLOAD_PHOTOS_SUCCESS,
              payload: response.data,
            });
          } catch (error) {
            dispatch({
              type: constants.UPLOAD_PHOTOS_FAILURE,
              payload: error,
            });
          }
        }
      };

    标签: javascript reactjs redux ecmascript-6


    【解决方案1】:

    在发出任何请求之前,您可以首先分析文件名并将数组分组为子数组,其中子数组的文件名具有模式“name-number.ext”。如果文件名没有编号,它们将最终成为子数组中的唯一条目。

    然后混合两个循环,forEach 作为外循环,for 作为内循环:

    export const uploadPhotos = 
      ({ photos, size, controller }) =>
      async (dispatch) => {
        // Identify the part of the file name that excludes the (optional) sequence number
        const keyedphotos = photos.map(photo => [photo.imageFileName.replace(/-\d+\.\w+$/, ""), photo]);
        // Create a group for each such prefix
        const map = new Map(keyedphotos.map(([key]) => [key, []]));
        // Populate those groups
        for (const [key, photo] of keyedphotos) map.get(key).push(photo)
        // And extract those groups into an array (of subarrays)
        const photoGroups = [...map.values()];
        let index = 0; // Keep the index counter separate
    
        photoGroups.forEach(async (photos) => { // Iterate the groups that can run in parallel
          for (const photo of photos) { // Iterate the photos that should run sequentially
            const id = index++; // Get the next unique id
            const formData = new FormData();
            formData.append(photo?.imageFileName, photo?.imageFile)
    
            dispatch({ type: constants.UPLOAD_PHOTOS_START, size });
            try {
              const response = await axios.post(
                `${API_URL}/photos/upload`,
                formData,
                {
                  onUploadProgress({ loaded, total }) {
                    dispatch(setUploadProgress({ id, loaded, total })); // Use id
                  },
                  signal: controller.signal,
                }
              );
    
              dispatch({
                type: constants.UPLOAD_PHOTOS_SUCCESS,
                payload: response.data,
              });
            } catch (error) {
              dispatch({
                type: constants.UPLOAD_PHOTOS_FAILURE,
                payload: error,
              });
            }
          }
        });
      }; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2020-12-06
      • 1970-01-01
      • 2020-08-25
      • 2018-02-08
      • 2020-06-18
      • 2020-03-13
      相关资源
      最近更新 更多