React Native AsyncStorage:从Promise对象访问值

Ste*_*rey 4 promise react-native

当我AsyncStorage.getItem()用来检索指定键的值(电子邮件地址)时,它返回一个Promise对象,如文档中所示.该值出现在对象中,如下所示:

{
  _45: 0
  _54: null
  _65: "testuser@test.com"
  _81: 1
}
Run Code Online (Sandbox Code Playgroud)

我可以通过调用可靠地访问此值,obj._65还是有其他方法可以实现此目的?

小智 10

AsyncStorage返回一个承诺.你可以使用.then获取价值

为例:

AsyncStorage.getItem('key').then((keyValue) => {
  console.log(keyValue) //Display key value
  }, (error) => {
  console.log(error) //Display error
});
Run Code Online (Sandbox Code Playgroud)


htt*_*ick -2

查看文档,您应该能够可靠地执行此操作,以从异步存储对象中检索数据:

try {
  const value = await AsyncStorage.getItem('@MySuperStore:key');
  if (value !== null){
    // We have data!!
    console.log(value._65);
  }
} catch (error) {
  // Error retrieving data
}
Run Code Online (Sandbox Code Playgroud)

但是,您必须在函数中使用它,async否则您将收到运行时异常。