Alan2
Alan2

Reputation: 24572

returning a promise that returns a promise?

I am a bit confused how to do this. Here is what I have:

resolve: {
   objectiveDetailsExam: ['objectiveDetailService', 'subjectService',
      function (objectiveDetailService: IObjectiveDetailService, subjectService: ISubjectService) {
         objectiveDetailService.getObjectiveDetailsExam("/" + subjectService.subject.id)
            .then((results): ng.IPromise<any> => {
               return objectiveDetailService.getObjectiveDetailsObjective("/" + objectiveDetailService.examId);
                            });
                    }]
        }

or should it be this which has a return before the objectiveDetailService.getObjectiveDetailsExam:

resolve: {
   objectiveDetailsExam: ['objectiveDetailService', 'subjectService',
      function (objectiveDetailService: IObjectiveDetailService, subjectService: ISubjectService) {
         return objectiveDetailService.getObjectiveDetailsExam("/" + subjectService.subject.id)
            .then((results): ng.IPromise<any> => {
               return objectiveDetailService.getObjectiveDetailsObjective("/" + objectiveDetailService.examId);
                            });
                    }]
            }

Either actually seem to work and as the call executes quickly I cannot see which is correct.

Can someone advise do I need one or two returns in the resolve which is supposed to return true or false?

Upvotes: 0

Views: 92

Answers (1)

Quentin Roy
Quentin Roy

Reputation: 7887

Returning a second promise in the 'body' of a first one (or in a function passed to then) will pipe the first with the second. The result of the promise resulting by the combination of both will be the result of the later one.

I would most likely prefer the later example. In the first example, you only return undefined which means that there is no way to know, from the outside, when your promise is actually resolved.

If you return it, you can get it back and pipe it to some code to be executed only when it has finished (or failed). That is the whole point of promises.

However, honestly, it is hard to figure out what your code is actually doing so returning something may actually be useless in this particular case. Just in case, if both works, I would still return it. Even if you don't directly have access to the returned promise, it may still be used behind the scene. In this case, the best would be to check how this value is used by your framework/library.

If you are interested to know more about promises and how to properly use them, here is a good article.

Upvotes: 3

Related Questions