简体   繁体   中英

React native - AsyncStorage, wait and sync

I'm use AsyncStorage, but I think I do not use correcly...

file 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;

File home.js

import Functions from 'Constants/functions';

export default class Home extends Component {


  constructor(props) {
    super(props);

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

console.warn(product) returned

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

I believe that this happens because I receive the object before it has been processed. Because if I put a console.warn before the return of the retrieveItem function it shows the object well...

是一个承诺,所以...您需要使用

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM