Berg_Durden
Berg_Durden

Reputation: 1781

How to make an entire script wait for response from Firebase?

I'm getting some data from Firebase and exporting this data to another script as an object, but since script-2.js is executed before the response in the script-1.js gets returned, I'm not able to get the data in time. I'm fairly new with both Firebase and promises and I'm having a hard time with them right now.

My project is something like this:

SCRIPT 1 (fetching data and storing it into fetchedData):

let fetchedData= {}

const db = firebase.firestore()

const getTechs = () => {
    return db.collection('techs').get()
}

window.addEventListener('DOMContentLoaded', async e => {
    const querySnapshot = await getTechs()

    querySnapshot.forEach(doc => {
        const key = Object.keys(doc.data())
        const value = Object.values(doc.data())
        fetchedData[key] = value
    })
    
})

export default fetchedData

SCRIPT 2 (Importing fetchedData from script-1.js

import fetchedData from './script-1.js'

console.log(fetchedData) // => here I have an empty object, since it's not populated yet.

//...do something with the data

If I was fetching the data and using it in the same script I could make this work, but I'm going to use fetchedData on multiple other scripts, so it would be nice not to have to fetch it on all of them.

How could I solve this?

P.S. I already tried with a hard coded object in script-1.js and worked fine, the problem really is what I described.

Upvotes: 0

Views: 54

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

You can export a Promise which would (eventually) resolve to your fetched data:

/* script 1 */

let resolve;
const promise = new Promise(r => resolve = r);

// eventually
resolve(data);

export default promise;

/* script 2 */
import fetchedDataPromise from './script-1.js';

// whenever you need it
const fetchedData = await fetchedDataPromise;

Alternatively, you could try to delay the execution of the 2nd script. Depending on how/when that gets executed, that might be possible.

Upvotes: 2

Related Questions