在世博会上使用打字稿调用返回承诺对象的异步函数

Calling async function returning promise object using typescript on expo

根据 activeStorage 上设置的条件,尝试 return 在 typescript expo 上实现不同的功能(带有视图)。

如果您查看代码,当调用 showIntro 时,我想显示从 getScreen 编辑的 return 的值,但是当我控制台日志时,它是return创建一个 promise 对象

当我在 getScreen 中控制日志 await AsyncStorage.getItem('showIntro'); 时,它给了我价值。 不确定这是错误还是代码有问题?

import AsyncStorage from '@react-native-community/async-storage'

const data = [{...}, {...}, {...}]

const getScreen = async () => {
  return await AsyncStorage.getItem('showIntro'); 
}

function App() {
  const [showIntro, updateShowIntro] = React.useState(getScreen());

  const onDone = () => {
     AsyncStorage.setItem('showIntro', false).then(()=>{});
     updateShowIntro(false);
  }

  return (
  { (showIntro) ? (
      <AppIntroSlider
        renderItem={renderItem}
        data={data}
        onDone={onDone}/>
      ) : (
        <ShowApp />
      )
    }
  );
 }

你的 getScreen returns a Promise 因为你正在使用 async/await。您需要做的是在您的组件首次加载到 React.useEffect 挂钩中时调用 getScreen,然后在它解析为您期望的任何值后更新您的 showIntro 状态.

使用 async/await 函数“等待”AsyncStorage.getItem("showIntro") 在返回之前用某个值解析实际上没有任何效果 - 你仍在处理一个 Promise 一旦“内部”Promise 完成。

来自 MDN:

The return value is a Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

import AsyncStorage from '@react-native-community/async-storage'

const data = [{...}, {...}, {...}]

// no need for `async/await` here, using `async/await`
// turns your `getScreen` function into a `Promise`, 
// you get the same exact result, so you might as well 
// call your `AsyncStorage.getItem("showIntro")` function
// directly in the `React.useEffect` hook rather than
// through this `getScreen` function
const getScreen = () => {
  return AsyncStorage.getItem("showIntro");
}

function App() {
  const [showIntro, updateShowIntro] = React.useState(null);

  React.useEffect(() => {
    getScreen()
      .then(result => {
        updateShowIntro(result);
      });
      .catch(/* handle errors appropriately */);

    // alternatively, just call `AsyncStorage.getItem("showIntro")` here
    // AsyncStorage.getItem("showIntro")
    //   .then(result => { updateShowIntro(result); })
    //   .catch(/* handle errors appropriately */);
  }, []);

  const onDone = () => {
     // should `updateShowIntro` be inside `then`?
     AsyncStorage.setItem('showIntro', false)
       .then(() => {
         updateShowIntro(false);
       })
       .catch(/* handle errors appropriately */);
  }

  return showIntro ? (
    <AppIntroSlider
      renderItem={renderItem}
      data={data}
      onDone={onDone}
    />
  ) : (
    <ShowApp />
  );
 }

参考文献: