Search code examples
breezedurandalhottowelq

What is the proper syntax to chain multiple queries together?


I'm using the HotTowel SPA template which makes use of Durandal. In my Durandal ViewModels I am using Breeze to get some data from the database.

I have a datacontext class that I put all my breeze queries in and the queries all follow the pattern like the following:

getAthletes: function (queryCompleted) {
            var query = breeze.EntityQuery.from("Athletes");
            return manager
                .executeQuery(query)
                .then(queryCompleted)
                .fail(queryFailed)
        }

Since I'm doing an asynchronous call in the activate method of the view model, I have to return the promise that comes back from these calls in the activate method.

Using a single query works great like this:

function activate() {
  datacontext.getAthlete(loadAthlete);
}

However, if I need to perform two queries I run into problems, but only in the release version of my application. I have tried doing this with the following syntax:

function activate() {
  datacontext.getAthlete(loadAthlete).then(datacontext.getOtherData(loadOtherData));
}

This will work fine in debug mode, but when I deploy it out to the server and my scripts get bundled, I get an exception which isn't very clear.

t is not a function

I've also tried chaining them together in my datacontext class like below, but I still get the same error.

getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
    var athleteQuery = breeze.EntityQuery.from("Athletes").where("id", "==", athleteId);
    var effortsQuery = breeze.EntityQuery.from("BestEfforts").where("athleteId", "==", athleteId);

    return manager.executeQuery(athleteQuery).then(athleteQueryCompleted)
        .then(manager.executeQuery(effortsQuery).then(effortsQueryCompleted))
        .fail(queryFailed);
}

So I'm assuming I just don't understand the Q.defer() enough to use it properly or there is something else going on.

What is the correct syntax to accomplish this?


Solution

  • Ok, thanks to RainerAtSpirit for pointing me in the right direction to find this. I looked at John Papa's jumpstarter examples and he has a datacontext that does this under the primeData function.

    So using the syntax he used there I was able to get it to work correctly like this:

    getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
        return Q.all([
                    datacontext.getAthlete(athleteId, athleteQueryCompleted),
                    datacontext.getAthleteEfforts(athleteId, effortsQueryCompleted)]);
    }
    

    I had seen the Q.all in the Q documentation but wasn't sure how to use it, but this example helped. I tested this and it works both in debug and release modes.