express async await
Here’s a quick example of using the JavaScript/ES2017 async/await
feature inside a Node Express app. async/await
is a way to force synchronous execution of asynchronous code. One benefit: avoiding promise pyramids of doom.
My use case is to gather a bunch of data together from separate api calls before doing some work and returning one result to the caller (especially if certain calls depend on data from previous calls before executing).
In our case, an axios request can fail, which is a rejected promise and needs to be caught, hence the try / catch
you see below. If I were working on a Express app long term I would probably work on a wrapper class similar to a Scala Either
or Try
which would provide an abstraction over these potentially unsafe i/o operations.
But for now, the example.
NOTE: this only works on newer versions of Node. I am running 8.5.0 in this case