0

I have the following code in angularjs:

TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime =new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());                     
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });

            console.log(eventName);
            console.log(events);
            // console.log(value);

             //value is the object!!
            })
             return events;
             $scope.$broadcast('eventSourceChanged',$scope.eventSource);

            })

         }

Everytime the forEach loop runs through my array of objects , vm.data, the console prints this:

console.log

My questions are :

1) Why are the details of the 4 objects being printed? Does it mean that for every object in the array it contains 4 other objects?

2) Is each object pushed to the events[ ] properly?

3) If the answer to question 2 is no, what should I do to resolve it?

EDIT: Updated code to using promise to return events array:

    //Calendar Controller
  .controller('CalendarCtrl', function ($scope,TimeSlotsModel,$rootScope,$q) {
    var vm = this;


    function goToBackand() {
        window.location = 'http://docs.backand.com';
    }

    function getAll() {
        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;
            });
    }

    function clearData(){
        vm.data = null;
    }

    function create(object) {
        TimeSlotsModel.create(object)
            .then(function (result) {
                cancelCreate();
                getAll();
            });
    }

    function update(object) {
        TimeSlotsModel.update(object.id, object)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function deleteObject(id) {
        TimeSlotsModel.delete(id)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function initCreateForm() {
        vm.newObject = {name: '', description: ''};
    }

    function setEdited(object) {
        vm.edited = angular.copy(object);
        vm.isEditing = true;
    }

    function isCurrent(id) {
        return vm.edited !== null && vm.edited.id === id;
    }

    function cancelEditing() {
        vm.edited = null;
        vm.isEditing = false;
    }

    function cancelCreate() {
        initCreateForm();
        vm.isCreating = false;
    }

    // initialising the various methods
    vm.objects = [];
    vm.edited = null;
    vm.isEditing = false;
    vm.isCreating = false;
    vm.getAll = getAll;
    vm.create = create;
    vm.update = update;
    vm.delete = deleteObject;
    vm.setEdited = setEdited;
    vm.isCurrent = isCurrent;
    vm.cancelEditing = cancelEditing;
    vm.cancelCreate = cancelCreate;
    vm.goToBackand = goToBackand;
    vm.isAuthorized = false;


    //rootScope refers to the universal scope, .$on is a receiver for the 
    //message 'authorized'
    $rootScope.$on('authorized', function () {
        vm.isAuthorized = true;
        getAll();
    });

    $rootScope.$on('logout', function () {
        clearData();
    });

    if(!vm.isAuthorized){
        $rootScope.$broadcast('logout');
    }

    initCreateForm();
    getAll();


    $scope.calendar = {};
    $scope.changeMode = function (mode) {
        $scope.calendar.mode = mode;
    };

    $scope.loadEvents = function () {
        $scope.calendar.eventSource = getEvents();
        $scope.$broadcast('eventSourceChanged',$scope.eventSource);

    };

    $scope.onEventSelected = function (event) {
        console.log('Event selected:' + event.startTime + '-' + event.endTime + ',' + event.title);
    };

    $scope.onViewTitleChanged = function (title) {
        $scope.viewTitle = title;
    };

    $scope.today = function () {
        $scope.calendar.currentDate = new Date();
    };

    $scope.isToday = function () {
        var today = new Date(),
            currentCalendarDate = new Date($scope.calendar.currentDate);

        today.setHours(0, 0, 0, 0);
        currentCalendarDate.setHours(0, 0, 0, 0);
        return today.getTime() === currentCalendarDate.getTime();
    };

    $scope.onTimeSelected = function (selectedTime) {
        console.log('Selected time: ' + selectedTime);
    };


    function getEvents(object){

      var deferred = $q.defer();

        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime = new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());                     
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });
            // console.log(eventName);
            // console.log(events);
            // console.log(value);
            // console.log(key);
            // console.log(value);

             //value is the object!!
            })

            deferred.resolve(events);

            // return events;


            })
            return deferred.promise;
            console.log(deferred.promise);


         }
cornstar94
  • 57
  • 2
  • 11
  • 1
    You're still returning an object from an asynchronous function call (`.all().then()`) which doesn't work: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron); Also anything after `return ...` is not reachable and therefor not executed – Andreas Dec 31 '15 at 09:15
  • 1
    Caveat: I haven't read your code in detail, but: Those little blue `i`s next to the logged objects mean something like "The object was re-evaluated when the details were expanded" (hover over it to get the tooltip for the exact wording) - ie it could have been modified _after_ it was logged, and you're seeing the updated object in the log. – James Thorpe Dec 31 '15 at 09:18
  • @andreas I've read the link but I am not sure how I should return my events array, taking into account that James is right that my objects are being pushed correctly and its just the console updating my log. – cornstar94 Dec 31 '15 at 09:47
  • Did you also read [How do I return the response from an asynchronous call?](http://stackoverflow.com/a/14220323/1331430) ? – Andreas Dec 31 '15 at 11:22
  • @andreas yes I did but I am using angularjs so I followed the example here instead [javascript - getting the return data of a async function inside a function](http://stackoverflow.com/questions/25301382/javascript-getting-the-return-data-of-a-async-function-inside-a-function) but its still not working. – cornstar94 Dec 31 '15 at 11:38
  • The function passed to `.then()` is executed when the asynchronous call in `.all()` has completed. You can only work with the returned data in this passed function. Either assign the events array to any angular-specific object/scope (I haven't work with angular yet...) or, as you changed the code to use a promise, resolve the promise passing the event data (where all the `// console.log()` calls are located). You would then have to call `getEvents().then(function(events) { ... });` – Andreas Dec 31 '15 at 12:22
  • thanks! i'll try again! – cornstar94 Dec 31 '15 at 12:53

1 Answers1

1

[!Removed old answer]

I believe James is right here the console might be the culprit, I just reproduced the same behaviour.the

Boris
  • 530
  • 4
  • 20
  • 1
    [Why do I need 50 reputation to comment? What can I do instead?](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead) – James Thorpe Dec 31 '15 at 09:29