Requested angularjs being executed first incorrectly

1

In a controller, I have two HTTP requests:

function findProfessionalEmail(professional) {
           EmailHunter.findProfessionalEmail(professional.company_name, professional.first_name,
                 professionalLastName).then(function (data) {
                    var score = data.data.data.score;

                    if (isProfessionalEmailScoreHigh(score)) {
                        vm.professional.email = data.data.data.email;
                    }
            });
        }

and

function checkAvailability(professional, callback) {
            findProfessionalEmail(professional);

            var cb = callback || angular.noop;
            CheckAvailability.save(getCheckAvailabilityDTO(vm.professional), function () {
                    console.log('Success!');
                    return cb();
            }, function (err) {
                console.log('Erro!');
                return cb(err);
            }).$promise;
        }

When invoking the second "checkAvailability ()" method, the system does not execute my request for the "findProfessionalEmail ()" method first, and always executes the "checkAvailability ()" request first.

Why this behavior? How can I fix it?

    
asked by anonymous 20.09.2016 / 22:10

1 answer

4

The problem is that you are getting lost in the concept of async calls .

See both EmailHunter.findProfessionalEmail and CheckAvailability.save make HTTP calls which by default are asynchronous calls, so you do not guarantee call order like you did, and it seems that findProfessionalEmail is doing more processing than CheckAvailability.save % so the response from save arrives first.

What you need to do is to call CheckAvailability.save within the .then of the EmailHunter.findProfessionalEmail call so you make use of the promises of angular .

The best thing to do would be

function checkAvailability(professional, callback) {

            var cb = callback || angular.noop;
            CheckAvailability.save(getCheckAvailabilityDTO(vm.professional), function () {
                    console.log('Success!');
                    return cb();
            }, function (err) {
                console.log('Erro!');
                return cb(err);
            }).$promise;
        }

function findProfessionalEmail(professional, checkAvailabilityCallBack) {
           EmailHunter.findProfessionalEmail(professional.company_name, professional.first_name,
                 professionalLastName).then(function (data) {
                    var score = data.data.data.score;

                    if (isProfessionalEmailScoreHigh(score)) {
                        vm.professional.email = data.data.data.email;
                    }

                    checkAvailabilityCallBack(vm.professional)
            });
        }

And call it like this:

findProfessionalEmail(professional, checkAvailability);
    
21.09.2016 / 14:16