4

As from the example from the docs

await User.query() returns a promise with an array of users.

await User.query().findById(1) returns a user with the ID of 1.

How does the User.query() know when a it needs to be executed or if it is chained.

I would assume that once User.query() is called, the request is already transmitted to the database server and thus cannot be modified. However, chaining it with .findById(1) modifies the request so that it builds the query with a condition where User.id = 1; and then transmits it to the DB server?. How does that work?

Ramil Amparo
  • 612
  • 1
  • 9
  • 25

1 Answers1

5

User.query() returns a query builder, where one can add as many more chained method calls as one likes:

query = User.query();
query.where('id', 1);
query.limit(1);

// also each method returns `this` as return value so chaining is possible

query.select('id', 'name').where('name', 'like', '%batman%')

Now that the query is complete and you like to execute the query builder and send query to the database you need to call .then() or for example resolve it with Promise.resolve(query) which implicitly calls query builder's .then method.

In your case you are using await to trigger the query which is effectively just syntactic sugar for ´Promise.resolve`

All following examples of executing the query are pretty much equivalent


// await with parenthesis underlining execution order of statements
res = await (User.query().select('name'));

// await without parenthesis with implicit execution order
res = await User.query().select('name');

// older way with thenables and promises
User.query().select('name').then(res => {
})

// another way with themables and promises
Promise.resolve(User.query().select('name')).then(res => {

})

So all of cases above calls .then method of the query builder to execute the query and .then returns a promise, which will resolve with the results read from DB.

Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70