1

AngularJS: Return values from function

How can I resolve this problem?.

   function byDepartment () {
            var result = null;
            deparmentService.query({
                codDepartment: vm.codDepartment.codDepartment,
                reportBycodDepartment: 1
            }, function (data) {
                var success = JSON.stringify(data.success);
                if (success === false) {
                    console.log(JSON.stringify(data.data));
                    result = data.message;
                } else {
                    result = data.data;
                    console.log('Always has a value: ' + result);
                }
            });
            console.log('Always null: ' + result);
            return result;
        }

The console of the Chrome answer this: Always null: null Always has a value: [object Object],[object Object]

I would like to use this value in the next function after:

  vm.updateChart = function () {
            vm.testValue = 0;
            if (!vm.codTestRoom) {
                console.log('consulta con departamento');
                vm.testValue = byDepartment();
            } else if (!vm.codEquipment) {
                console.log('Consulta con departamento y testRoom');
                vm.testValue = byDepartmentAndTestRoom();
            } else {
                console.log('Consulta con departamento, testRoom y Equipo');
                vm.testValue = byDepartmentAndTestRoomAndEquipment();
            }
            // console.log('Valor: ' + JSON.stringify(vm.testValue));
        };

After this with vm.testValue I'm going to draw a chart with chart.js..

Thanks.

Community
  • 1
  • 1
Miguel-Ángel
  • 57
  • 2
  • 11
  • 1
    This is an issue with understanding sync processes vs async process and how the javascript event stack queues said events. I would take some time to read up: https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node – Shadowfool May 16 '18 at 17:15
  • Why would `JSON.stringify` ever return a value of `false`? – georgeawg May 24 '18 at 20:41

1 Answers1

1

This is happening because you are doing async calls but handling it like it's sync. In angularjs, as in regular javascript, one solution to wait on async calls is to use promises.

In angularjs, promises are easy to create by the $q provider which will help you create new promises with the method defer(). Here's how you could implement it (remember to inject $q)

function byDepartment () {
    var deferred = $q.defer();
    var result = null;
    deparmentService.query({
        codDepartment: vm.codDepartment.codDepartment,
        reportBycodDepartment: 1
    }, function (data) {
        var success = JSON.stringify(data.success);
        if (success === false) {
            deferred.reject(data.message);
        } else {
            deferred.resolve(result.data);
        }
    });
    return deferred.promise;
}

When invoking the byDepartment() method you need to tell what should happend when the returned promise is succesful and when its not by passing one success function and one error function to the then() method on the promise

vm.updateChart = function () {
    vm.testValue = 0;
    if (!vm.codTestRoom) {
        console.log('consulta con departamento');
        byDepartment()
        .then(
            function (result) {
                vm.testValue = result;
            },
            function (message) {
                console.log(error);
            }
        );
    } else if (!vm.codEquipment) {
        console.log('Consulta con departamento y testRoom');
        vm.testValue = byDepartmentAndTestRoom();
    } else {
        console.log('Consulta con departamento, testRoom y Equipo');
        vm.testValue = byDepartmentAndTestRoomAndEquipment();
    }
    // console.log('Valor: ' + JSON.stringify(vm.testValue));
};
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • I'm trying with this but and error apperars. Then is not a fucntion... I'm working with it. I must to learn this.... The error is: TypeError: Cannot read property 'then' of undefined at Object.vm.updateChart (sparePartReportController.js:122) – Miguel-Ángel May 16 '18 at 18:14
  • @Miguel-Ángel Update the answer, I had a typeo. It should be return deferred.promise;. Please try again and I advice you to implement it like this instead of the accepted answer. If you start with callbacks you are down the rabbit hole – Marcus Höglund May 16 '18 at 18:37
  • Thank you so much, All works perfectly. I'm going to use both to learn a little bit of this topic... – Miguel-Ángel May 17 '18 at 14:49
  • Why would `JSON.stringify` ever return a value of `false`? – georgeawg May 24 '18 at 20:40
  • I'll try without it, I'm a begginer, a lot fo things are not clear for me. – Miguel-Ángel May 25 '18 at 13:54