【问题标题】:React native - AsyncStorage, wait and syncReact native - AsyncStorage,等待和同步
【发布时间】:2019-03-21 20:17:18
【问题描述】:

我正在使用 AsyncStorage,但我认为我没有正确使用...

文件functions.js

import { AsyncStorage } from 'react-native';

const Functions = {
    async storeItem(key, item) {
      try {
AsyncStorage.setItem()
          var jsonOfItem = await AsyncStorage.setItem(key, JSON.stringify(item));
          return jsonOfItem;
      } catch (error) {
        console.warn(error.message);
      }
    },
    async retrieveItem(key) {
      try {
        const retrievedItem =  await AsyncStorage.getItem(key);
        const item = JSON.parse(retrievedItem);
        return item;
      } catch (error) {
        console.warn(error.message);
      }
    }
}

export default Functions;

文件 home.js

从“常量/函数”导入函数;

export default class Home extends Component {


  constructor(props) {
    super(props);

    product = Functions.retrieveItem('products');
   console.warn(product);
  }
}

console.warn(product) 返回

{"_40":0,_65":1,"_55":null,"_72":null}

我相信发生这种情况是因为我在处理对象之前收到了它。因为如果我在retrieveItem 函数返回之前放置一个console.warn,它会很好地显示对象......

【问题讨论】:

  • retrieveItem 会返回 promise,如果你想接收数据,你必须在异步函数上使用 await Functions.retrieveItem('products')

标签: javascript react-native promise async-await asyncstorage


【解决方案1】:

是一个 Promise 所以......你需要使用

Functions.retrieveItem('products').then((res) => { //do something with res });

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2016-09-16
    • 2021-03-26
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多