0

I am working on a JavaScript project. I am using firebase as my backend. I wrote this code and I am having trouble understanding why the

alert(name)

returns undefined but it shouldn't. The firebase data is not empty. Can someone help me figure it why the global name variable won't change?

var database = firebase.database();
var ref2 = database.ref('information/');

var id;
var name;

ref2.on("value", function(one) {

    one.forEach(function(two) {

        if (typeof two.val().Id !== 'undefined') {
            id = two.val().Id;

            function program() {
                return new Promise(function(resolve, reject) {
                    try {
                        var database = firebase.database();
                        var ref = database.ref("users/" + id + "/");

                        ref.on('value', function(user) {
                            resolve(user.val().name);
                        })
                    } catch (e) {
                        reject(e)
                    }
                });
            }

            program().then(function(result) {
                name = result; //I initialize the name variable here and note that if I do alert (result), it does alert a string but it wont change the name variable. 
            }).catch(function(error) {
                console.log(error)
            })

        }

        alert(name); //returns undefined. Why?

    });

});
};
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • if `program().then(function(result) ` does not finish before you alert the name then you will get `undefined` – Andrew Lohr Dec 04 '17 at 18:00
  • you should be alerting the name in the promise's `.then` right under you assign `name = result` – Andrew Lohr Dec 04 '17 at 18:01
  • I know by doing that, it works but in future I am going to have the alert statement replaced with something like string =name + otherVariables + "\n". And at that time the name will return undefined which I want to avoid. Also I am curious why it wont change the name. How should I change my code. –  Dec 04 '17 at 18:12

0 Answers0