Performing asynchronous lookups

Koa's use of promises via async functions does make a very clear declarative syntax when it comes to common scenarios involving asynchronous operations.

For instance, let's consider our routes/index.js file, imagine we had to look up the title from a database.

With async/await it would look something like the following:

const router = require('koa-router')() 
 
router.get('/', async function (ctx, next) { 
  const title = await pretendDbLookup('title') 
  ctx.body = ` 
    <html> 
      <head> 
        <title> ${title} </title> 
        <link rel="stylesheet" href="styles.css"> 
      </head> 
      <body> 
        <h1> ${title} </h1> 
        <p> Welcome to ${title} </p> 
      </body> 
    </html> 
  ` 
}) 
 
function pretendDbLookup () { 
  return Promise.resolve('Koa') 
}  
 
module.exports = router 

We can check this by copying the app folder from the main recipe to async-ops-app and placing the previous code in routes/index.js.

As long as the asynchronous operation returns a promise, we can use await inside Koa middleware and route handlers to perform asynchronous operations in a syntactically aesthetic manner. On a side note, pretendDbLookup could have been written as async function pretendDbLookup () { return 'Koa' } and the net result would be the same (a promise that resolves to the string Koa).