Transaction API misleading
See original GitHub issueFirst off thanks for Knex! 😃
The transaction API has a promise-like API (then()
, catch()
) that suggests it’s exposing a promise for the eventual committal or rollback of the transaction. Instead, however, it’s a stateful API with nothing to do with promises - every time you call it something happens and a different promise is returned!
If you consider the root idea of promises it is that they represent a future value, or a failure to provide that value. Calls to then()
are entirely divorced from time - e.g you should be able to call then()
any number of times, before, after, and during the asynchronous operation it represents, and get the same result every time.
I’d be happy to contribute to fix up this aspect of the API. I just wasted a heap of time because something that looked like a promise wasn’t one.
Issue Analytics
- State:
- Created 9 years ago
- Comments:18 (16 by maintainers)
Top GitHub Comments
You are not alone. A
.then
in promise-land shouldn’t have side-effects, but the knex API does.A transaction is either committed or rejected, so seems like good mapping to promise semantics. Each transaction is triggered via
commit()
at some future point, so it could create a deferred inside its constructor and expose its promise viathen()
.On the query front, it’s clearly trickier as you want to be able to reuse the same builder. A solution is to put the execution behaviour behind something like an
run()
method: no more verbose and makes the builder/query separation clear:Having things exposing a
then()
without promise semantics will just get more confusing as time goes on and promises are more widely used/understood (i.e ES6 adoption).