等待map中的所有异步函数完成执行

时间:2020-05-26 10:45:08

标签: javascript reactjs react-native async-await react-redux

我想完成映射内 ALL 异步函数的执行,然后更改组件的状态。如果您可以帮助我,我只保留了一部分代码。

我要做的就是每次用户取消权限时都显示我自己的“权限”屏幕。

为简单起见,我有这个:

const permissions = {
    cameraRoll: {
        iconType: "ionicon",
        iconName: "ios-images",
        title: "Enable camera roll",
        subtitle:
          "To upload content from your Gallery, you have to granted the camera roll permission",
        buttonText: "Enable camera roll",
        checkPermission: checkCameraRollPermission,
        requirePermission: requireCameraRollPermission,
      },
    };
}


const checkCameraRollPermission = async () => {
    const { status, canAskAgain } = await Permissions.getAsync(
      Permissions.CAMERA_ROLL
    );
    return { status, canAskAgain };
  };


  const requireCameraRollPermission = async () => {
    const { status, canAskAgain } = await Permissions.askAsync(
      Permissions.CAMERA_ROLL
    );
    return { status, canAskAgain };
  };


/* I HAVE TO WAIT FOR ALL THE FUNCTIONS TO FINISH EXECUTION
FOR EACH OBJECT ON THE MAP BUT THIS IS NOT WORKING :( */
getMissingPermissions = () => {
    // Only check permissions on the foreground
    if (AppState.currentState.match(/active/)) {
      // We have to empty the current missing permssions and recalculate them
      const permissionsArray = [];
      Promise.all(
        Object.keys(permissions).map((key) => {
          permissions[key].checkPermission().then(({ status }) => {
            if (status !== "granted") {
              permissionsArray.push(permissions[key]);
            }
          });
        })
      ).then(() => {

        this.setState({
          missingPermissions: permissionsArray,
        });
      });
    }
  };

有什么想法吗?谢谢

1 个答案:

答案 0 :(得分:1)

使用Promise.all,您需要以数组形式提供诺言。目前,您没有从地图中返回任何导致问题的原因。

您也可以只使用嵌套的promise中的返回所需值,而无需使用PermissionsArray变量,该值将在Promise.all(...).then(...)响应中提供

getMissingPermissions = () => {
    // Only check permissions on the foreground
    if (AppState.currentState.match(/active/)) {
      // We have to empty the current missing permssions and recalculate them
      Promise.all(
        Object.keys(permissions).map((key) => {
          return permissions[key].checkPermission().then(({ status }) => {
            if (status !== "granted") {
              return permissions[key];
            }
            return;
          });
        })
      ).then((res) => {
        const permissionsArray = res.filter(Boolean)// Filter out undefined values
        this.setState({
          missingPermissions: permissionsArray,
        });
      });
    }
  };