4 ms·
I'd assert that inside routes you actually don't want to be sync, yet async/await lets you write async code with the simplicity of writing sync code. Consider
by hombre_fatal 8y ago
I'd assert that inside routes you actually don't want to be sync, yet async/await lets you write async code with the simplicity of writing sync code.
Consider the simple example of just running two unrelated database/network queries at the same time which is basically a ubiquitous desire when writing a web service:
const [user, stats] = await Promise.all([
db.getUser(42),
cache.fetchStats()
])
And now consider a case where you want to issue four database queries, but you don't want the route to take four connections out of the pool at once, instead ensuring that it only uses two:
// This fn is built into Bluebird and trivial to find 8-line impl for.
// getA..getD are just functions that return promises so they can be
// created lazily.
const [a,b,c,d] = await Promise.map([getA, getB, getC, getD],
(fn) => fn(),
{ concurrency: 2 }
)
What I would simply assert is that these sorts of things are really nice to have in your toolbox when writing I/O code like a networked program, and I don't think there exists a simpler async abstraction for it than Node. And I certainly would not have said this until Node had promises and async/await.
- toasterlovin 8y ago99% of the endpoints I write are two steps: load some data from the database, then use that to render HTML, JSON, CSV, etc. I really do not want to encounter any of the myriad of bugs that asynchronous execution makes possible. And the best way for that to happen is if nothing is async.