等待映射内的所有异步函数完成执行

我想在映射内完成所有异步函数的执行,然后更改组件的状态。我给你留了一个减少的代码部分,以防你能帮助我。


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


为了简化,我有这个:


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,

        });

      });

    }

  };

有什么想法吗?谢谢


POPMUISE
浏览 67回答 1
1回答

至尊宝的传说

您需要以数组的形式提供承诺。目前,您没有从地图中返回任何内容,这是导致问题的原因。Promise.all此外,代替使用 permissionsArray 变量,您可以简单地从嵌套 promise 中返回所需的值,该值将在响应中可用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,        });      });    }  };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript