I am currently working with an AngularJS factory that retrieves data from a PouchDB database.
angular.module('app.factories', [])
.factory('ProgressDBFactory', function () {
var factory = {};
var pouchDb = new PouchDB('ProgressDB');
factory.getAllData = function() {
var dbOptions = {};
dbOptions.include_docs = true;
return pouchDb.allDocs(dbOptions).then(function(res) {
return res.rows;
});
};
return factory;
})
In order to populate the $scope.progressData
in my controller with the data from the PouchDB, I have implemented the following code in my controller:
.controller('ProgressController', function($scope, ProgressDBFactory) {
$scope.progressData = {};
var progPromise = ProgressDBFactory.getAllProgressData();
progPromise.then(function(res) {
$scope.progressData = res;
console.log($scope.progressData); // POINT A <= Here it prints all the results from the database.
});
console.log($scope.progressData); // POINT B <= here it just prints an empty object
})
When testing the above code, I noticed that at POINT A it correctly prints the result from the database. However, at POINT B it prints an empty object. Additionally, POINT B gets printed in the console before POINT A, indicating that the promise may not have finished executing by the time POINT B is executed. As a newcomer to JavaScript, I find this behavior confusing. Can someone provide clarification and suggest a solution? Your help would be greatly appreciated.