I have a button that triggers a function which uses a promise to fetch and display data from Firebase in an HTML environment (I'm incorporating AngularJS, Ionic, and Firebase).
The issue is this: if I do not include a .then(function(){}) right after it, the promise runs asynchronously, requiring me to click the button again for the data to show up on the webpage.
I aim to place the data into the scope following the promise that retrieves data from Firebase. Strangely enough, it only seems to work when I add a .then function afterwards.
However, the data appears normally in the console but does not reflect in the HTML (which makes me suspect that the function isn't properly attached to the scope).
Below is the code snippet:
$scope.displayChat = function () {
var userId = firebase.auth().currentUser.uid; // Get ID
var deferred = $q.defer()
var db = firebase.database();
var ref = db.ref("12346787");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
$scope.chatArray = snapshot.val();
deferred.resolve()
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
})
return deferred.promise.then(function(){
// Removing this empty .then(function(){}) function
// will result in asynchronousity.
// just "return deferred.promise;" doesn't work.
})
}
Any suggestions or solutions? I am relatively new to promises so I haven't found any related resources. Thanks.