首页 > 解决方案 > 函数外的javascript变量(带有异步/等待)?

问题描述

我有以下由于语法错误而无法工作的代码(在异步函数之外等待)

  1. 如何使用 await 定义变量并将其导出?

  2. 当我定义这样的变量并从其他文件中导入它时,该变量是只创建一次(第一次读取文件时?)还是每次导入时都创建?

代码..

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

标签: javascript

解决方案


  1. await只能在async函数中使用。无法使用await语法导出变量。

  2. 由于await无法导出 with ,因此很难说RemoteConfig.build()每次都会调用 。如果我们假设,你写了firebaseConfig = RemoteConfig.build();. 该函数将在评估模块时调用一次。

这是一种解决方法:

您可以定义一个函数来设置firebaseConfig并在应用程序启动时调用它。

所以:

export let firebaseConfig;

export async function setFirebaseConfig() {
    firebaseConfig = await RemoteConfig.build();
}

这将允许您不RemoteConfig.build()多次调用。也firebaesConfig可以在没有await语法的情况下导出。


推荐阅读