I've read many answers to this question but I just don't get it. Where does the promise go? I made a simple factory with an async call to a cloud database:
app.factory('asyncFactory', function() {
let toController = function() {
firebase.database().ref('en').once('value') // get the array from the cloud database
.then(function(snapshot) { // take a snapshot
console.log(snapshot.val()); // read the values from the snapshot
return snapshot.val(); // this returns later
});
return 47 // this returns immeadiately
};
return {
toController: toController // why is this necessary?
}
});
I call it from my controller:
$scope.words = asyncFactory.toController();
console.log($scope.words);
Here's the response:
As you can see, 47 returns to the controller immediately. If I comment out return 47 then the factory returns undefined. Later the async data logs but doesn't return to the controller. I use promises every day but I can't figure out where the promise goes.
Second question: do I need the line toController: toController ? Can I get rid of it?
Thanks!
