MikkoP
MikkoP

Reputation: 5092

Executing queries simultaneously and returning after all queries are ready

I find myself often in a situation where I need to query for multiple models in the database before sending them to be rendered in HTML. What I have done is

ModelA.findById({ ... }).then(function(modelA) {
    ModelB.findById({ ... }).then(function(modelB) {
        return both modelA and modelB
    });
});

This has a couple of problems:

  1. The second query is executed after the first one has returned. Because they don't depend on each other, this just adds a delay. The queries should be executed at the same time.
  2. Having multiple queries, this gets pretty messy. Imagine the following

ModelA.findById({ ... }).then(function(modelA) {
    ModelB.findById({ ... }).then(function(modelB) {
        ModelC.findById({ ... }).then(function(modelC) {
            ModelD.findById({ ... }).then(function(modelD) {
                ModelE.findById({ ... }).then(function(modelE) {
                    ModelF.findById({ ... }).then(function(modelF) {
                        return all models
                    });
                });
            });
        });
    });
});

How do I execute the queries simultaneously and continue the page rendering only after all queries have been executed?

Upvotes: 0

Views: 42

Answers (1)

Adam
Adam

Reputation: 5233

You can use Promise.all in this case, all your queries will be executed simultaneously, but the then function will be executed when all your queries returned.

var queries = [
    ModelA.findById({...}),
    ModelB.findById({...}),
    ModelC.findById({...}),
    ModelD.findById({...}),
    ModelE.findById({...}),
    ModelF.findById({...})
];

Promise.all(queries).then(function (results) {
    console.log(results); // [modelA, modelB ...]
});

You should also read about javascript promises.

Upvotes: 1

Related Questions