React Native在导出之前等待AsyncStorage

时间:2016-11-28 16:57:21

标签: firebase react-native async-await export asyncstorage

根据AsyncStorage的用户设置首选项,我需要初始化两个Firebase环境中的一个。我有来自我用来设置Firebase数据库的javascript文件的片段,但是你可以清楚地看到它会在await调用时给我一个语法错误。

导出firebase符号的最佳方法是什么,但只有在进行了相应的initializeApp调用之后?

谢谢,

红色

import firebase from 'firebase';
import { AsyncStorage } from 'react-native';
import { FIREBASE_CONFIG, FIREBASE_CONFIG_DEMO, DATA_ENVIRONMENT_STORAGE_KEY } from '../../../shared/env';


async function initializeFirebase()
{
    value = await AsyncStorage.getItem(DATA_ENVIRONMENT_STORAGE_KEY);
    if ((value == null) || (value == 'live'))
        firebase.initializeApp(FIREBASE_CONFIG);
    if (value == 'demo')
        firebase.initializeApp(FIREBASE_CONFIG_DEMO);
}
await initializeFirebase();

export var db = firebase.database();
export default firebase;

1 个答案:

答案 0 :(得分:0)

如果我理解的是正确的,你想要的是初始化firebase,然后创建一个db引用并导出它。

试试这个:

<强> initializeFirebase.js

import firebase from 'firebase';
import { AsyncStorage } from 'react-native';
import {
    FIREBASE_CONFIG,
    FIREBASE_CONFIG_DEMO,
    DATA_ENVIRONMENT_STORAGE_KEY
} from '../../../shared/env';

async function initializeFirebase() {
    const value = await AsyncStorage.getItem(DATA_ENVIRONMENT_STORAGE_KEY);

    let firebaseConfig = null;
    if ((value === null) || (value === 'live')) {
        firebaseConfig = FIREBASE_CONFIG;
    } else if (value === 'demo') {
        firebaseConfig = FIREBASE_CONFIG_DEMO;
    }

    if (firebaseConfig !== null) {
        await firebase.initializeApp(firebaseConfig);
        return firebase.database();
    }
}

export default initializeFirebase;

<强> someOtherFile.js

import initializeFirebase from './initializeFirebase.js';

async someOtherFunction() {
    // ...    

    const database = await initializeFirebase();

    // ... do something with 'database'
}