Let us consider the following basic Express+node script.
(You can download this script..)
Normally, the handler of an end-point (epRootHandler) cannot be an async function due to how the Express framework was written. However, by using the express-async-handler node module, one can now specify async end point handlers. The following shows the previous script, but with minimal changes to enable the use of async end-point handlers.
(You can download this script.)
Note that const asyncHandler = require(’express-async-handler’) brings the module in.
Furthermore, asyncHandler is a wrapper that makes it possible to use an async handler as an end-point handler.
Despite the enabling of using async handlers, this new script behaves exactly the same as the previous one.
The following "prankster" script makes use of using await inside the async end-point handler to delay the response by 5 seconds.
(You can download this script.)
Note that the async function delay is written using anonymous functions to make it more concise. The delay function is not our focus here, however.
The way epRootHandler utilizes await is of interest here. In reality, there are few reasons why a server may want to delay a response. However, there are many situations where a Express+node script may need to perform a lengthy asynchronous operations.
Lengthy asynchronous operations include querying a database, using RESTful API to query another server, performing a lengthy file operations, and etc. If node modules provide async APIs to these oeprations, then it becomes a simple matter to use await in a Express end-point handler.