Haitham Hirt
Haitham Hirt

Reputation: 35

How to return Array from Firebase Snapshot

I'm trying to retrieve some Data from Firebase (which works perfectly), but my colleague needs that I return the value of a snapshot as an Array, so that he can use it in another file. And as far as I know, it's impossible knowing that the value event is Asynchronous.

here's an example:

function getData() {
let current = [];
qRef.on("value", function (snapshot) { //qRef is the reference to my DB
    current = snapshot.val();
}, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});
return current; //expected value is the returned data from the snapshot
}

Is there any alternative solution? Thanks.

Upvotes: 1

Views: 2355

Answers (2)

Atul
Atul

Reputation: 430

if its not a snapshot , suppose a get function,then you can use this:-

function getData() {
    return new Promise(function(resolve, reject){
        let current = [];
        qRef.on("value", function (snapshot) { //qRef is the reference to my DB
            current = snapshot.val();
            resolve(current);
        }, function (errorObject) {
            console.log("The read failed: " + errorObject.code);
            reject({
                error: true
            })
        });

    })
}

call it like

getData.then(function(current){
    desired_variable = current
})

since its a snapshot you can pass a callbak function and call it everytime. callback function will set the data to the desired variable

 function getData(callback) {
    let current = [];
    qRef.on("value", function (snapshot) { //qRef is the reference to my DB
        current = snapshot.val();
        // write logic for current array
        callback(current);
    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
        reject({
            error: true
        })
    });
}

it will be called like

getData(function(current){
       desired_variable = current;
})

hope it solves your issue

Upvotes: 0

Sidney
Sidney

Reputation: 4775

You're right, you can't directly return the value because it's asynchronous.

Instead, you should make use of Promises:

function getData() {
  return qRef
    .once('value')
    .then(snapshot => snapshot.val())
    .then(value => [ value ])
}

Notice that I'm using .once() instead of .on(). .on() is for listening for changes, .once() is for just retrieving the value on-demand. Also, .on() doesn't use promises because a promise means "some async work will happen, then you'll get a result". Listening for a value might mean the callback is triggered many times.

Upvotes: 4

Related Questions