Promise 返回未定义的 AsyncStorage

Hie*_*ero -3 javascript reactjs react-native asyncstorage

我有一个反应本机应用程序,我在其中进行一些身份验证。

我有以下代码,用于检查令牌是否未过期且可用。

export const isLogged = () => {

  AsyncStorage.getItem('@token')
    .then( token => {

      if (typeof token !== 'undefined') {

        if (tokenExpired(token)) {

          return false

        }

        return true

      }

      return false

    } )
    .catch( error => {

      return false

    } )

}
Run Code Online (Sandbox Code Playgroud)

但在我的代码中,如果我这样做:

let isUserLogged = isLogged()
console.log(isUserLogged) // -> returns undefined, but should return true because the token is there and its not expired.
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么会这样,我做错了什么?

tri*_*cot 5

您正在尝试同步获取只能异步获取的结果。

像这样更改您的代码:

  1. return在此调用之前添加:

    AsyncStorage.getItem('@token')
    
    Run Code Online (Sandbox Code Playgroud)

    这将使你的isLogged函数返回一些东西:一个承诺

  2. 在您的主代码中使用此承诺:

    isLogged().then( isUserLogged => { 
        console.log(isUserLogged);
    });
    
    Run Code Online (Sandbox Code Playgroud)

事实上,你的函数isLogged返回一个承诺(即当你返回它时),这是链接的一个例子。