【问题标题】:Why getItem return 'Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, }' with asyncStorage in my code?为什么 getItem 在我的代码中使用 asyncStorage 返回 'Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, }'?
【发布时间】:2021-12-10 06:27:45
【问题描述】:

我是 react native 的新手,我尝试使用 AsyncStorage 存储所选语言,但有一个我不明白的问题。

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');

结果是:

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

我想知道为什么 'c'console 会先出现,为什么会返回? 请帮忙!

【问题讨论】:

    标签: react-native async-await asyncstorage


    【解决方案1】:

    因为,getData() 是一个异步函数。

    试试这个

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

    而不是

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

    【讨论】:

      【解决方案2】:

      由于 getData 是一个异步函数,如果你正在调用另一个异步函数,你也可以这样尝试:

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

      但对于您示例中的当前代码

      这是你需要调用的方式:

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

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2022-01-14
        • 1970-01-01
        • 2021-03-02
        • 2022-01-05
        • 2021-04-21
        • 2021-12-20
        • 2021-11-26
        相关资源
        最近更新 更多