Home > Software design >  Why getItem return 'Promise { "_U": 0, "_V": 0, "_W": null, "
Why getItem return 'Promise { "_U": 0, "_V": 0, "_W": null, "

Time:10-25

I'm new to react native, I try to store with AsyncStorage the selected language but I have a problem that I don't understand.

import * as Localization from 'expo-localization';
import i18n from 'i18n-js';
import { en, fr } from '../i18n/supportedLanguages';
import AsyncStorage from '@react-native-async-storage/async-storage';

i18n.fallbacks = true;
i18n.translations = { en, fr };
i18n.locale = Localization.locale;

const storeData = async () => {
  try {
    const exist = await AsyncStorage.getItem('selectedLanguage');
    console.log('a',exist, 'a');
    if (exist == null) {
      await AsyncStorage.setItem(
        'selectedLanguage',
        i18n.locale
      );
    }
  } catch (error) {
  }
};

const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('selectedLanguage');
      if (value !== null) {
        console.log('b',value,'b');
        return value;

      }
  } catch (error) {
  }
};

storeData();
const thing = getData();
console.log('c',thing,'c');

The result is :

c Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
} c
a fr-FR a
b fr-FR b

I would like to know why the 'c'console come in first and why it return that? Please, help!

CodePudding user response:

Because, getData() is an async function.

try this

getData().then(thing => console.log('c', thing, 'c'))

instead of

const thing = getData();
console.log('c',thing,'c');
  • Related