Resolution of multiple promises in rubeprovider

So, I wanted to make 2 HTTP calls in order to get some groups and questions from my server, and both of these problems were resolved in the router so that the corresponding controller would not load before I had the appropriate data.

In my other controllers, I always worked with an initalData object to store data.

Part of permission:

resolve: { initialData: ["GroupsService" "QuestionsService", function (GroupsService, QuestionsService) { return { questions: QuestionsService.getAll(), groups: GroupsService.getAll() }] } 

When I tried to access the data in the controller using initialData.questions and initialData.groups, I, however, accepted 2 promises instead of data, even though the callback from http was registered before the controller was instantiated.

 QuestionsCtrl.$inect = ["DialogsService", "initialData", "QuestionsService"]; function QuestionsCtrl(DialogsService, questions, groups, QuestionsService) { //Initialdata object which has 2 Promise properties //This logs AFTER the callback in both http callbacks console.log('controller initialized', initialData); 

When I replaced the code with this (didn't use the initialData object, instead returned two other objects, it worked:

  resolve: { questions: function (QuestionsService) { //$http call for all questions return QuestionsService.getAll(); }, groups: function (GroupsService) { //$http call for all groups return GroupsService.getAll(); } } 

Does anyone have a logical explanation why, in the first case, I returned promises (despite the fact that the data was actually present on the client), and the second worked flawlessly?

+6
source share
2 answers

When you pass resolve to a route, it calls $q.all for it implicitly for you . Therefore, when you return multiple values ​​in a solution, it waits for them to complete.

In your example β€” you just returned an object containing several promises β€” you did not wait for them, so it resolved immediately with promises.

Of course, you can clearly expect them too:

  initialData: ["a" "b","$q" function (a, b, $q) { return $q.all({ questions: a.getAll(), groups: b.getAll() }); }] 
+8
source

If you want to decide to wait, you need to return the promise, in your first case it is not a promise, rather it is just an object, it usually has 2 objects, but promises, but angular won Not sure what ... If you want return it as the only solution, you can use:

 return $q.all({ key1: promise, key2: promise }); 

and add $ q as a dependency

Another thing is that promises do not turn them into initial values, when the data is received from the server, they remain promises, in case of permission angular will dig out the allowed value and provide these instead of promises. And again, we need to get back to the fact that angular should know that it is dealing with promises.

+2
source

Source: https://habr.com/ru/post/982519/


All Articles