0

Sample

Please consider this Plunk.

Background

The Plunk is a seriously simplified sample of what I need to do. Basically I need to get a person record with validation result included. This result will also include class information, so that the controller can assign proper styling to indicate mandatory status (or not).

The issue

The most important function in the sample is this one, the self.Get will use the validation logic and result a result.

self.Get('0f8fad5b-d9cb-469f-a165-70867728950e').then(function(result){
  $scope.person = result.person;

  $scope.validationResult = result.ValidateResult;
});

As you can see (because the form has correct values) $scope.person is loaded correctly, the $scope.validationResult however is not.

The question

I suspect there's a timing issue with the consecutive async calls, how can I fix this Plunk so that everything works correctly?

Nesting async calls in each other would be 'one' solution, I guess, but given the number of calls being made, that would not solve everything and the code would become highly unreadable.

0

2 Answers 2

1

For multiple async calls I would suggest to use array of promises:

var promises = [];
promises.push(service1.get(...))
promises.push(service2.get(...))
promises.push(service3.get(...))

return $q.all(promises);
Sign up to request clarification or add additional context in comments.

5 Comments

How can I solve dependencies in this setup? I mean, self.LoadPersonDetailProxy needs person, validationService.ValidateAsync needs personDetailProxy.
service1.get(...).then(service2.get).then(service3.get)
Isn't there a better option than nesting? And, doesn't this also break the need for an array?
@Spikee: That's not nesting. It's chaining - the solution to nesting (why promises were created in the first place). Nesting is get(get(get(get())))
Ok, but it still makes the code hard to read if you have to do it a lot.
0

So, how do I convert the following code to use chaining, while keeping all dependencies intact?:

self.Get = function (personId) {
    // 1. Init
    var defer = $q.defer();
    var asyncCallsResult = {};

    // 2. Get person
    var person = self.GetTestPerson();
    asyncCallsResult.person = person;

    self.LoadPersonDetailProxy(person).then(function(personDetailProxy) {
        $scope.personDetailProxy = personDetailProxy;
    });

    validationService.ValidateAsync($scope.personDetailProxy).then(function (validateResult) {
        asyncCallsResult.ValidateResult = validateResult;
    });

    defer.resolve(asyncCallsResult);

    return defer.promise;
}

Comments

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.