I'm pretty new to the MEAN stack and I've come across some confusing stuff regarding async tasks and callbacks. I'm using the meanjs.org boilerplate, and I'm sure this is a pretty simple question, but so far I haven't found any answers regarding why this callback isn't working.
On the Angular controller I'm trying to call the API for retrieving a single object from Mongo
$scope.find = function(callback) {
$scope.stock = Stock.query();
callback();
};
Calling this function from the ng-init of the page so that the object is loaded.
<section ng-controller='StockController' ng-init='find(initialize)'>
The initialize function (the callback) checks if there is no such object in Mongo and if there isn't one, it creates it:
$scope.initialize = function(){
if($scope.stock._id == null){
$scope.saveInDatabase();
}
};
The query() method is factoried into the module as such:
angular.module('inventario').factory('Inventario', ['$resource',
function($resource) {
return $resource('inventario/:inventarioId', { inventarioId : '@_id' }, { update : { method : 'PUT' }, query : { method : 'GET', isArray : false } } );
}
The problem is that when the initialize function is being called, the $scope.stock object is always empty and new objects are being saved on each page refresh. I assume this is because the initialize function is being called before the Stock.query() task finishes, but I can't really understand why. I would appreciate any help understanding why this is the case and if I am applying the callback wrong (this is a concept I have not yet fully grasped).