【问题标题】:React Native async await call return errorReact Native 异步等待调用返回错误
【发布时间】:2019-09-29 06:57:38
【问题描述】:

await 外的函数:返回错误不能使用关键字 await 请帮帮我...


I18n.defaultLocale = 'tr'
await AsyncStorage.getItem('locale').then((value) => {
 I18n.locale = value        
}).done();


I18n.fallbacks = true;
I18n.translations = { en, tr };

const currentLocale = I18n.currentLocale();

export function strings(name, params = {}) {
  return I18n.t(name, params);
};

export default I18n;

【问题讨论】:

    标签: react-native async-await expo


    【解决方案1】:

    你必须用 await/async 做这样的事情:

    var getItem = async function() {
      // await can be used here
      await AsyncStorage.getItem('locale').then((value) => {
        I18n.locale = value        
      }).done();
    }
    

    然后这样称呼它:

    getItem(); // sync
    

    await getItem(); // in another async function
    

    编辑:使用异步功能,您可以“做同样的事情”而不是无异步功能。只是 await 需要特殊包装。

    【讨论】:

    • 谢谢getItem();调用其他文件? a.js - getitem 函数 b.js - 调用 a.js 调用 getitem 函数?
    • 如果你想在另一个文件中重用它,只需导出/导入函数
    【解决方案2】:

    async 函数可以包含一个 await 表达式,该表达式暂停 async 函数的执行并等待传递的 Promise 的解析,然后恢复异步函数的执行并返回解析后的值。

    请记住,await 关键字仅在 async 函数中有效。 如果你在 async 函数体之外使用它,你会得到一个 语法错误。

    使用async/await时不需要使用then

    更多详情见async function on MDN Web docs

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 2019-08-02
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多