Home > Enterprise >  How to wait for onValue to return value from Firebase Realtime Database in nodejs
How to wait for onValue to return value from Firebase Realtime Database in nodejs

Time:11-08

I have a getData function witha onValue function from Firebase. But when I call it, it does not wait for the onValue to finish, with the consequence of giving undefined back.

Here is the getData function:

function getData(path) {
    try {
        const reference = ref(database, path);
        onValue(reference, (snapshot) => {
            const data = snapshot.val();
            console.log('DATA: '   data);
            return data;
        }, (error) => {
            console.error(error);
            return undefined;
        });
    } catch (error) {
        console.error(error);
        return undefined;
    }
    console.log('END!');
}

and when I call the function, the console looks like this:

END!
DATA: *[correct data]*

I already tried to make it a variable instead of a function. Does someone know how I can make it wait for onValue to finish.

CodePudding user response:

If you want to only get a value once, you should use get() instead of onValue.

function getData(path) {
    try {
        const reference = ref(database, path);
        return get(reference).((snapshot) => {
            const data = snapshot.val();
            console.log('DATA: '   data);
            return data;
        }, (error) => {
            console.error(error);
            return undefined;
        });
    } catch (error) {
        console.error(error);
        return undefined;
    }
    console.log('END!');
}

All the logging makes the function quite a lot more complex than needed, so distilled to its essence this is:

function getData(path) {
    const reference = ref(database, path);
    return get(reference).((snapshot) => snaphot.val());
}
  • Related