簡體   English   中英

如何從異步 function 獲取返回值到 React Native 中的變量?

[英]How to get a return value from async function to a variable in React Native?

我有一個帶有身份驗證過程的 React Native 應用程序。 為了獲得身份驗證,我使用異步存儲來存儲令牌並檢索令牌。

我創建了一個從異步存儲中獲取令牌的方法,但問題是,我不能通過將令牌分配給另一個變量來在其他函數中使用它。 我創建的方法的 function 調用始終返回 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` }} />
    }
  }} />
)

我該如何解決這個問題?

Once you have a Promise, all the code depending on the promise will need to be chain using Promise.then(functionThatDoesMoreThings) or you will need to await Promise... and then do things.

大多數人更喜歡異步/等待......所以在你的情況下,它看起來像:

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` }} />
    }
  }} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM