首页 > 解决方案 > 如何从异步函数获取返回值到 React Native 中的变量?

问题描述

我有一个带有身份验证过程的 React Native 应用程序。为了获得身份验证,我使用异步存储来存储令牌并检索令牌。

我创建了一种从异步存储中获取令牌的方法,但问题是,我不能通过将令牌分配给另一个变量来在其他函数中使用它。我创建的方法的函数调用总是返回一个 Promise 而不是令牌。

应用程序.js

const getToken = async () => {
  var value = "";
  try {
    await AsyncStorage.getItem('accessToken').then(val => {
      value = val;
    })
  } catch (e) {
    console.log("error getting token", e)
  }
  console.log("token", value) // here I can see the correct token
  return value;
}

const AuthRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => {
    if (Auth.isAuthenticated()) {

      var idToken = getToken().then(t => { return t });
      console.log("token", idToken) // here it is a Promise

      if (idToken) {
        return <Component {...props} />
      }
      return <Redirect to={{ pathname: `/signup` }} />
    }
    else {
      // return <Component {...props} />
      return <Redirect to={{ pathname: `/signup` }} />
    }
  }} />
)

我该如何解决这个问题?

标签: javascriptreactjsreact-native

解决方案


一旦你有了 Promise,所有依赖于 Promise 的代码都需要使用 Promise.then(functionThatDoesMoreThings) 链接起来,或者你需要等待 Promise... 然后执行操作。

大多数人更喜欢异步/等待......所以在你的情况下,它看起来像:

const AuthRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={async props => {
    if (Auth.isAuthenticated()) {

      var idToken = await getToken();
      console.log("token", idToken) // it should print the token

      if (idToken) {
        return <Component {...props} />
      }
      return <Redirect to={{ pathname: `/signup` }} />
    }
    else {
      // return <Component {...props} />
      return <Redirect to={{ pathname: `/signup` }} />
    }
  }} />

推荐阅读