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?
});
});
};