Using Firebase Database after Firebase Initializing after

399 views
Skip to first unread message

lavanya burlagadda

unread,
Jun 22, 2022, 9:06:48 AM6/22/22
to Firebase Google Group
In our code we are using firebase 8.6.1

I want to initialize firebase only when required, so after initializing firebase with firebase.initializeApp(config) when I directy access firebase.database will there be any issue like,

If firebase.initializeApp(Config) returns a promise then we need to wait else firebase won't be initialized and if we access firebase.database it throws an error.

Help me out whether we need to use await for the firebase methods

Sergio Fernandez

unread,
Jun 24, 2022, 3:24:33 PM6/24/22
to Firebase Google Group

Hello! you can have firebase initialized without problems because it doesn't influence anything in the project.

In the first image, I have created a file called index.js where I make the connection to firebase. every time the project is started or rendered, the connection is established automatically

In the second image I show the structure of the firebase folder. consists of the file endoints, index and query. endpoints are the calls I use to firestore, for collection and document I want to access. query is the firebase function, which then makes it possible to call via endpoints. I show you image of the query

What I'm trying to explain is, as long as you don't call the firestore functions, nothing you've said before should give you trouble.
Captura.PNG
Captura.PNG
Sin título.png

Tracy Hall

unread,
Jun 24, 2022, 3:24:33 PM6/24/22
to Firebase Google Group
Almost all Firebase functions return a promise; whether you use .then() or async/await doesn't matter  (While the current "best practice" is to use async/await, the reality is that it is just "syntactic sugar" on top of promises).

As to waiting - you are right that there is often NOT a top-level async/await  - it depends on your boot sequence.  What you CAN do is something like this (obviously this example is for Stripe):

```
import { loadStripe } from "@stripe/stripe-js";

export let stripe = null;
export let stripe_started = false;
export let stripe_running = false;

(async () => {
  try {
    stripe = await loadStripe("pk_test_GDHxwe8K5eX0MvBUhnx5FtrY00mAd6B0IT");
    stripe_running = true;
  } catch (err) {
    stripe_running = false;
  } finally {
    stripe_started = true;
  }
})();
```
This uses a self-executing closure to asynchronously run the initialization, and simple "flags" to let other functions know if it's complete.

In my particular case, I am *essentially* doing:
```
firebase.InitializeApp(config).then(() => {...more code...});
```
...where the "more code" effectively sets an "enabled" flag (not really, but it amounts to the same thing).
Reply all
Reply to author
Forward
0 new messages