当我尝试访问从异步方法返回的值时,为什么会得到未定义的输出

Why am i getting an undefined output when I try to access value returned from async method

我有以下方法,其中 returns 在名为 localStorage 的不同文件中包含 3 个字段的对象:

    const getUserProfileData = async () => {
    try {
        await AsyncStorage.getItem(CONSTANTS.USER_PROFILE).then((item) => {
        let retrievedProfile = JSON.parse(item);
        return retrievedProfile;
        });
    } catch (e) {
        throw e;
    }
    };

这是我的文件 profile.js:

  useEffect(() => {
    const retrieveProfileData = async () => {
      let retProfile = await localStorage.getUserProfileData();
      console.log("check what:  ",retProfile);
    };
    retrieveProfileData();
  }, []);

在使用效果中,当我尝试注销结果时,我得到的输出是:

check what:   undefined

我已经阅读过关于与此类似问题的其他论坛,但我似乎没有注意到我哪里出错了?

    const getUserProfileData = async () => {
        return AsyncStorage.getItem(CONSTANTS.USER_PROFILE);
    };

    useEffect(() => {
    const retrieveProfileData = async () => {
        try {
        let retProfile = JSON.parse(await localStorage.getUserProfileData());
        console.log("check what:  ",retProfile);
        } catch (error) {
            // handle error
        }
    };
    retrieveProfileData();
    }, []);

我认为这与您混合使用 async.then() 有关。试试这个方法:

const getUserProfileData = async () => {
    try {
        const result = await AsyncStorage.getItem(CONSTANTS.USER_PROFILE)
        const retrievedProfile = JSON.parse(result);
        return retrievedProfile;
    } catch (e) {
        throw e;
    }
};