【问题标题】:Promise return undefined AsyncStorage承诺返回未定义的 AsyncStorage
【发布时间】:2016-09-03 09:41:37
【问题描述】:

我有一个 react-native 应用程序,我在其中进行一些身份验证。

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

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.

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

【问题讨论】:

  • 你必须连接另一个then 舞台并在那里进行检查。

标签: javascript reactjs react-native asyncstorage


【解决方案1】:

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

像这样更改您的代码:

  1. 在此调用之前添加return

    AsyncStorage.getItem('@token')
    

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

  2. 在你的主代码中使用这个承诺:

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

您的函数 isLogged 返回一个承诺(即当您返回它时)这一事实是 chaining 的一个示例。

【讨论】:

    【解决方案2】:

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

    由于您已经在这里操作 Promises,您可以只返回您的 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 的信息。

    【讨论】:

    • 非常感谢,有没有办法让这个同步?并直接从函数返回?
    • 不,documentation 声明 AsyncStore 是(顾名思义)异步存储。如果你希望它是同步的,你必须找到一个替代品(但我不知道有没有)。
    猜你喜欢
    • 2015-09-27
    • 2020-03-18
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多