0

I'm quite new to promises. I have a hard time trying to update an object used in my view from 2 chained promises :

function Test($resource, FC, UserDetailsService) {
    'ngInject';

    var self = this;

    self.data = {

    };

    function getTestData() {
        firstPromise.then(function(response) {

            //I want self.data to be displayed in my view
            angular.extend(self.data, response);
            //Now my view should display my object

            resource().get(user)
                .$promise.then(function(responsePts){
                    //And THEN update/refresh my view here
                    angular.extend(self.data, responsePts);

            });
        });
    };

    self.getTestData = getTestData;

};

EDIT : firstPromise is exposed in another service, and used by other services :

$resource(apiUrl).get(user).$promise.then(function(bookData){
    angular.extend(self.bookings, bookData);
});

In my controller :

function TestController(Test) {
    'ngInject';

    var $ctrl = this;

    $ctrl.testData = {};

    Test.getTestData();
    $ctrl.testData = Test.data;

};

Instead self.data will not be displayed until the resolution of the second promise. How can I make my object available for my controller directly when the first promise is resolved ?

redAce
  • 1,558
  • 4
  • 14
  • 24

1 Answers1

1

It the firstPromise is a $q Service promise, the view should be updating. Since the view is not updating, use $q.when() to convert the unknown promise to a $q Service promise:

function getTestData() {
    //firstPromise.then(function(response) {
    $q.when(firstPromise).then(function(response) {

        //I want self.data to be displayed in my view
        angular.extend(self.data, response);
        //Now my view should display my object

        //return to chain
        return resource().get(user).$promise;
    }).then(function(responsePts){
        //And THEN update/refresh my view here
        angular.extend(self.data, responsePts);

    });
};

$q Service promises are integrated with the AngularJS framework and its digest cycle.

$q.when(value)

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

-- AngularJS $q Service API Reference - $q.when

georgeawg
  • 48,608
  • 13
  • 72
  • 95