Sandra Lopez
Sandra Lopez

Reputation: 107

access function return values with firebase database

hello im trying to get the values that my function return, i get them in console log, but how can i access them when calling my function? function:

function getprofile(useruid) {
    return firebase.database().ref('users/'+useruid+'/')
    .once('value')
    .then(function(bref) {
        var username= bref.val().username;
        var provider= bref.val().provider;
        var submitedpic=bref.val().profilepic;
        var storageRef = firebase.storage().ref();
        console.log("The current ID is: "+useruid+" and the current username is: "+username+'/provider is: '+provider+'/pic is :'+submitedpic);
    });
}

i call my function like this:

 getprofile(userid);

Upvotes: 3

Views: 3111

Answers (1)

Sébastien
Sébastien

Reputation: 12139

You have to return a value from your .then() callback

function getprofile(useruid) {
    return firebase.database().ref('users/'+useruid+'/')
    .once('value')
    .then(function(bref) {
        var username= bref.val().username;
        var provider= bref.val().provider;
        var submitedpic=bref.val().profilepic;
        var storageRef = firebase.storage().ref();
        console.log("The current ID is: "+useruid+" and the current username is: "+username+'/provider is: '+provider+'/pic is :'+submitedpic);
        // return the values here, in the form of an object
        return {
            useruid: useruid,
            username: username,
            provider: provider,
            submitedpic: submitedpic,
            storageRef: storageRef
        };
        // or simply return the value returned by firebase
        /*
        return bref;
        */
    });
}

.once() returns a promise, so when you get the return value from getprofile(), you will have a promise which yields the actual result from your firebase call:

getprofile(userid).then(function(data) {
    // use data here
})

Upvotes: 3

Related Questions