Question

This is very closely related to this question, however I have been unable to successfully modify/implement the solution.

I am building a SPA (Single Page Application). So this project includes several javascript libraries. This particular instance I am "Lazy Loading" breeze entities.

Here is my code. I have two functions that work to create the array of promises.

getChildrenV2: function (entity) {
    var self = this,
        deferred = Q.defer(),
        p = entity.entityAspect.loadNavigationProperty("Children").then(function (data) {
            deferred.resolve(data);
        });
    return deferred.promise;
},

getChildren: function (entity) {
    var self = this;
    return self.getChildrenV2(entity).then(
        function (data) {
            return Q.all(data.results.map(
                function (e) {
                    console.log(e);
                    self.getChildren(e);
                }
            ));
        });
},

From what I understand of the solution in the SE question linked above, I should be able to do this (below) and all of the "Children" will have been loaded.

getChildren(entity).then(function () {
    console.log("All Children have been loaded");
});

I'm obviously misunderstanding something in either the solution to the SE linked above or the way I have written my recursive function.

Edit

After reviewing the answers provided by @Bergi and @Esailija I have refactored my code as follows.

getChildren: function (entity) {
    var self = this;
    return entity.entityAspect.loadNavigationProperty("Children").then(
        function (data) {
            return Q.all(data.results.map(
                function (e) {
                    console.log(e);
                    return self.getChildren(e);
                }
            ));
        });
},

If you notice I got rid of the getChildrenV2 function to make the code IMO more concise (taking the suggestion to shorten the function and make it cleaner from @Esailija).

My initial issue was resolved by @Bergi and fixed by simply returning the recursive function call return self.getChildren(e);.

Thank you for your help.

Was it helpful?

Solution 2

You don't return anything from your map. Change it to

… data.results.map(function (e) {
    console.log(e);
    return self.getChildren(e);
//  ^^^^^^
}) …

Apart from that minor issue, it looks good should work. Notice @Esailija's answer though.

OTHER TIPS

Please change getChildrenV2

to

getChildrenV2: function (entity) {
    return entity.entityAspect.loadNavigationProperty("Children");
}

Not only is it shorter, it will no longer swallow any errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top