【问题标题】:Why is my function returning undefined despite printing out correctly尽管打印正确,为什么我的函数返回未定义
【发布时间】:2021-12-28 23:28:27
【问题描述】:

代码

函数返回

  async getData(key, setHook) {
    try {
      await AsyncStorage.getItem(key).then((response) => {
        console.log("getData response: " + response); // prints out correctly
        setHook(response); // sets my hook as undefined?
      })
    } catch(e) {
      console.log("AsyncStorage getData: error: " + e);
    }
  }

接收函数


const key = 'key';

const Home = ( {navigation} ) =>  {
  ...
  const [totalBreaks, setTotalBreaks] = useState('0'); // the hook I use in the above function

 // on mount setCounter
 useEffect(() => {  
      setCounter();
 }, []);


 async function setCounter () {
    await asyncStorageInterface.getData(key, setTotalBreaks);
    console.log("total breaks: " + totalBreaks); // returns undefined on mount... when it shouldn't
    if(totalBreaks === null || totalBreaks === undefined) {
      await asyncStorageInterface.storeData(key, '0');
      await asyncStorageInterface.getData(key, setTotalBreaks);
    }
    console.log("total breaks: " + totalBreaks);
  }

问题

我不知道问题是什么...我花了将近 6 个小时试图解决这个问题,有人可以帮助我吗?如果可能的话,请深入解释问题所在,以便我可以在某处记录它。谢谢。

【问题讨论】:

  • 注意:使用thenawait 是一种反模式。
  • 试试这个:const result = await AsyncStorage.getItem(key); setHook(result);

标签: javascript asynchronous async-await


【解决方案1】:

您的totalBreaks 在您设置之前已被读取。很简单:

const result = {};
const {val} = result;
result.val = 'foo';
console.log(val); // you will still get undefined.

这与异步无关

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2014-06-04
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 2022-01-16
    相关资源
    最近更新 更多