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.

2
  • 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: stackoverflow.com/questions/16336367/… Commented May 16, 2018 at 17:15
  • Why would JSON.stringify ever return a value of false? Commented May 24, 2018 at 20:41

1 Answer 1

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));
};
Sign up to request clarification or add additional context in comments.

5 Comments

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 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
Thank you so much, All works perfectly. I'm going to use both to learn a little bit of this topic...
Why would JSON.stringify ever return a value of false?
I'll try without it, I'm a begginer, a lot fo things are not clear for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.