Reputation: 9435
With normal promises a promise will resolve as soon as it is able to do so, once the current code has halted. Consider the following pseudo code:
const p = SomePromiseDoingLoad();
calculatethings();
await sleepPromise();
//during sleep the promise p might/will have resolved already.
await p; //awaiting just makes *sure* the promise is already executed
However how does this translate to a query builder like knex? There seems to be no way to prevent a promise from executing?
const p = knex.select('*').from('table');
//p could be executed now already.
const data = await gatherDataFromWebsite();
//p most probably will have resolved??
p.limit(data.limit) // ???
What would happen in above, and further how do I even prevent this from potentially happening? Node is afterall always allowed to resolved the promise as soon as it can, so just chaining dots could let it resolve?
const p = knex.select('*').from('table').limit(5);
let q = knex.select('*');
q = q.from('table');
q = q.limit(5);
Or what magic trickery is knex doing behind the schemes to postpone execution?
Upvotes: 7
Views: 3065
Reputation: 113866
Knex query builder is not a Promise, but something that Promise/A+ spec calls thenable
.
Knex only executes network I/O when you call .then()
on a query builder object. As long as you have not called .then()
on a query builder object it will simply chain and return a query builder object instead of a Promise.
The await
keyword resolves the query builder and internally calls a its .then()
method therefore using await
with a knex
query builder object will also cause it to return a promise.
It is not postponing execution. Instead execution is triggered by the query builder object's (not Promise) .then()
method.
Upvotes: 17