title: you might be better off without async/await publishedAt: 06.12.2017 16:10 ...
With es2017, async/await is the new hot sh**. And with Babel it is tempting to use it everywhere.
/*
* If you rewrite this express route in es2017...
*/
router.get('/posts', (req, res) => {
axios.get(`https://api.github.com/gists/${gistId}`)
.then(response => response.data.files)
// Convert object to array and get file contents
.then(files => Object.keys(files).map(key => files[key]))
.then(files => files.map(file => file.content))
// Extract meta data with marked (markdown converter)
.then(contents => contents.map(content => marked(content)))
// Only use published posts and sort by publishedAt
.then(posts => posts.filter(p => p.meta.publishedAt))
.then(posts => posts.sort((a, b) => a.meta.publishedAt < b.meta.publishedAt))
// Return posts
.then(posts => res.json(posts))
// Give a nice error messages if something broke
.catch((err) => {
res.status(500).send('Wups! Something broke.')
console.error(err.message, err.stack)
})
}
/*
* ...you get this, which is equivalent in functionality.
*/
router.get('/posts', (req, res) => {
try {
const response = await axios.get(`https://api.github.com/gists/${gistId}`)
const files = response.data.files
// Convert object to array and get file contents
const filesArray = Object.keys(files).map(key => files[key])
const contents = filesArray.map(file => file.content)
// Extract meta data with marked (markdown converter)
const posts = contents.map(content => marked(content))
// Only use published posts and sort by publishedAt
const filtered = posts.filter(p => p.meta.publishedAt)
const sorted = filtered.sort((a, b) => a.meta.publishedAt < b.meta.publishedAt)
// Return posts
res.json(sorted)
} catch (err) {
// Give a nice error messages if something broke
res.status(500).send('Wups! Something broke.')
console.error(err.message, err.stack)
}
}
Besides the fact that the async/await version uses 14 lines of code compared to 13 with plain old promises, async/await is much less intuitive and less reader friendly. It is hard to see how to control flow works and you have to constantly come up with new names for variables.
Next time you get to choose your stack, rethink the benefits and drawbacks of async/await.