如何从导入中调用异步函数?
How to call async function from import?
我有这个异步代码函数可以从 AsyncStorage 获取 lang var。我想在 construct(?) 方法中的每个应用程序页面上调用此函数。但是当我尝试调用它时,它看起来像代码 运行 同步,而我的 loadedLang 是 = { _45: 0, _81: 0, _65: null, _54: null }。如何以正确的方式做到这一点?谢谢
main.js
import load from "./components/languageLoad"
constructor(props) {
super(props);
let loadedLang = load();
console.log("LOADED", loadedLang);
this.state = {
settings: 1,
deviceLocale: "EMPTY"
};
}
languageLoad.js
import React, { Component } from 'react';
import { AsyncStorage} from 'react-native';
import Lang from 'react-native-i18n'
export default load = async () => {
try {
const customLang = await AsyncStorage.getItem('customLang');
if (customLang !== null && customLang !== undefined && customLang !== "") {
deviceLocale = customLang;
}
} catch (error) {
deviceLocale = Lang.locale.split("-")[0] || "uk";
}
console.log("------------", deviceLocale, '-------------');
console.log("------------", Lang.t('aboutAppText') , '-------------');
Lang.locale = deviceLocale;
return Lang;
}
async
函数需要用 await
调用,并且只能从异步函数内部调用。
JS 构造函数不能是异步的。因此,您将重组代码以不同的方式工作。要么在构造函数外部加载数据,要么在构造函数中有一个匿名的自执行异步函数来加载数据并存储它。当然,class 的其余部分需要处理数据可能不存在的事实。
我有这个异步代码函数可以从 AsyncStorage 获取 lang var。我想在 construct(?) 方法中的每个应用程序页面上调用此函数。但是当我尝试调用它时,它看起来像代码 运行 同步,而我的 loadedLang 是 = { _45: 0, _81: 0, _65: null, _54: null }。如何以正确的方式做到这一点?谢谢
main.js
import load from "./components/languageLoad"
constructor(props) {
super(props);
let loadedLang = load();
console.log("LOADED", loadedLang);
this.state = {
settings: 1,
deviceLocale: "EMPTY"
};
}
languageLoad.js
import React, { Component } from 'react';
import { AsyncStorage} from 'react-native';
import Lang from 'react-native-i18n'
export default load = async () => {
try {
const customLang = await AsyncStorage.getItem('customLang');
if (customLang !== null && customLang !== undefined && customLang !== "") {
deviceLocale = customLang;
}
} catch (error) {
deviceLocale = Lang.locale.split("-")[0] || "uk";
}
console.log("------------", deviceLocale, '-------------');
console.log("------------", Lang.t('aboutAppText') , '-------------');
Lang.locale = deviceLocale;
return Lang;
}
async
函数需要用 await
调用,并且只能从异步函数内部调用。
JS 构造函数不能是异步的。因此,您将重组代码以不同的方式工作。要么在构造函数外部加载数据,要么在构造函数中有一个匿名的自执行异步函数来加载数据并存储它。当然,class 的其余部分需要处理数据可能不存在的事实。