Patrick McDermott
Patrick McDermott

Reputation: 1220

Returning a value from a request within a function

I am making a call from a controller in AngularJS, which passes data to a service to get a response in which I need to then check with a condition.

Controller

patents.forEach(function(item){ //patents is resolved in a router file which returns a number of items from a request
    item.renewalProgress = patentsService.phaseProgress(item);
})

Service

factory.phaseProgress = function(item) {

var progress = function(item)
    factory.fetchCostAnalysis(phase.id)
        .then(
            function(response){
                var progress;
                    switch(response.currentcostBand) {
                        case 'Green':
                        progress = 0;
                            break;
                        case 'Amber':
                         progress = 20;       
                            break;
                        case 'Red':
                        progress = 40;           
                            break;
                        case 'Blue':
                        progress = 60;
                            break;
                        case '
                        progress = 80;
                    }
                 return progress
                }, function(errResponse){
                    console.log('no')
                }
            )


    return progress;

}

The value is coming back as undefined.

Question

How do I return a value to the controller from the service? If anyone can suggest a better approach even?

Upvotes: 0

Views: 46

Answers (1)

anteAdamovic
anteAdamovic

Reputation: 1468

In your service you have an asynchronous function which returns a promise, that means when you get to that part, your process continues and that part of code inside then() will execute at a later time.

If you wish to WAIT for promise execution you can use Deffer from AngularJS.

Read up on AngularJS Promises: promises-in-angularjs-the-definitive-guide

Upvotes: 1

Related Questions