承诺 return 未定义的 AsyncStorage

Promise return undefined 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

    } )

}

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

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

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

您的 isLogged 函数是一个异步函数,也就是说 - 它对您在函数执行的确切时刻可能不可用但时间延迟的值进行操作。

由于您已经在此处对 Promises 进行操作,因此您可以只 return 您的 AsyncStorage 承诺链的结果,然后在调用 isLogged() 函数时附加额外的处理程序,如下所示:

// inside your isLogged() function
return AsyncStorage.getItem('@token')
  .then(...)
  ... rest of your code unchanged ...

// when invoking isLogged()
isLogged().then((isLogged) => {
    console.log("is user logged: ", isLogged);
});

您还应该阅读 JavaScript 中有关 Promises 的更多信息。

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

像这样更改您的代码:

  1. 在此调用之前添加return

    AsyncStorage.getItem('@token')
    

    这将使您的 isLogged 函数 return 成为某种东西:承诺

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

    isLogged().then( isUserLogged => { 
        console.log(isUserLogged);
    });
    

事实上,您的函数 isLogged return 是一个承诺(当您 return 它时,就是 chaining 的一个例子。