javascript - 函数外的javascript变量(带有异步/等待)?
问题描述
我有以下由于语法错误而无法工作的代码(在异步函数之外等待)
如何使用 await 定义变量并将其导出?
当我定义这样的变量并从其他文件中导入它时,该变量是只创建一次(第一次读取文件时?)还是每次导入时都创建?
代码..
import _ from 'lodash'
import remoteConfig from '@react-native-firebase/remote-config'
class RemoteConfig {
constructor() {
if (__DEV__) {
//Fetch, no cache. activate
remoteConfig().fetchAndActivate(0)
} else {
//Fetch, cache for 5 minutes and activate
remoteConfig().fetchAndActivate()
}
}
static async build() {
await remoteConfig().setConfigSettings({
minimumFetchIntervalMillis: 300000,
})
return new RemoteConfig()
}
setDefaults(defaults) {
remoteConfig().setDefaults(defaults)
}
getValues(keys) {
return _.pick(remoteConfig().getAll(), keys)
}
getValue(key) {
return remoteConfig().getValue(key)
}
}
export let firebaseConfig = await RemoteConfig.build()
我正在使用它import {firebaseConfig} from path/to/thefile
解决方案
await
只能在async
函数中使用。无法使用await
语法导出变量。由于
await
无法导出 with ,因此很难说RemoteConfig.build()
每次都会调用 。如果我们假设,你写了firebaseConfig = RemoteConfig.build();
. 该函数将在评估模块时调用一次。
这是一种解决方法:
您可以定义一个函数来设置firebaseConfig
并在应用程序启动时调用它。
所以:
export let firebaseConfig;
export async function setFirebaseConfig() {
firebaseConfig = await RemoteConfig.build();
}
这将允许您不RemoteConfig.build()
多次调用。也firebaesConfig
可以在没有await
语法的情况下导出。
推荐阅读
- java - 在 Intent 服务中设置静态字段的值
- python - 为什么在生成随机数时迭代次数很重要?
- javascript - 如何防止 html 元素转义父级?(安全)
- javascript - Django:如何使视图仅在重定向时被访问
- wordpress - 获取分类术语的完全匹配,而不是部分匹配
- google-apps-script - 无法从 onEdit 内部调用我的函数
- javascript - 为什么 get request 在 python 中有效,但在 javascript 中无效?
- python - Python 语音识别 KeyError BufferedReader
- python - 如何将 Pypi (__init__.py) 上的代码与子文件夹中的类一起打包
- vue.js - 如何使卡固定在整个容器中?