Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is child state resolve functions are executed before parent state promises are resolved

I'm using ui-router v0.2.13. This page states that:

All resolves on one state will be resolved before moving on to the next state, even if they aren't injected into that child

And more

All resolves for all the states being entered are triggered and resolvesd before the transition will enter any states (regardless of the resolve being injected somewhere)

However, in my case, child state resolve function is executed before parent's resolve promise is resolved. How is this possible?

Here:

$stateProvider
    .state('route1', {
        url: "/route1",
        templateUrl: "route1.html",
        resolve: {
            parent: ["$timeout", "$q", function ($timeout, $q) {
                var d = $q.defer();
                $timeout(function () {
                    d.resolve();
                }, 5000);
                return d.promise;
            }]
        }
    })
    .state('route1.list', {
        url: "/list",
        templateUrl: "route1.list.html",
        controller: function ($scope) {
            $scope.items = ["A", "List", "Of", "Items"];
        },
        resolve: {
            child: function () {
                alert("I'm shown before `parent` resolved");
            }
        }
    });

If you navigate to /route1/list the alert is immediately shown instead of waiting 5 seconds until a parent resolve promise is resolved.

like image 554
Max Koretskyi Avatar asked Aug 10 '15 18:08

Max Koretskyi


1 Answers

All resolves are guaranteed to be resolved before transition is actually performed. But the statements don't point out that resolve functions will be called synchronously. And that's is correct.

According to the ui-router source code, invocables are resolved as "parallel" as possible. Only ones dependent on other invocables (either from parents or from current state declaration) will be executed after their dependencies are resolved.

So the only way to make child invocable to be invoked after parent is resolved is to specify parent as dependency of child invocable.

.state("route1",{
   //..
   resolve: {
        parent: ["$timeout", "$q", function ($timeout, $q) {
            var d = $q.defer();
            $timeout(function () {
                d.resolve();
            }, 5000);
            return d.promise;
        }]
    }
 })
 .state("route1.list",{
    //...
    resolve: {
         child: ["parent", function(parent) {
             //will be called only after parent is resolved
         }]
 })

Excerpt from the GitHub resolve.js source code comments:

Invocables are invoked eagerly as soon as all dependencies are available. This is true even for dependencies inherited from a parent call to $resolve.

like image 72
FunkyOne Avatar answered Sep 18 '22 16:09

FunkyOne