Asynchronous handlers
All of the examples shown so far in this chapter assume that handlers are synchronous. In a real application, many handlers will need to be asynchronous.
Nest.js provides a number of approaches to write asynchronous request handlers.
Async/await
Nest.js has support for async request handler functions.
In our example application, the entriesService.findAll()
function actually returns a Promise<Entry[]>
. Using async and await, this function could be written as follows.
import
{
Controller
,
Get
}
from
'@nestjs/common'
;
@
Controller
(
'entries'
)
export
class
EntryController
{
@
Get
()
async
index
()
:
Promise
<
Entry
[]
>
{
const
entries
:Entry
[]
=
await
this
.
entryService
.
findAll
();
return
entries
;
}
Async functions have to return promises, but using the async/await pattern in modern JavaScript, the handler function can appear to be synchronous. Next, we’ll resolve the returned promise and generate the response...