DEV Community

Discussion on: Express Middleware for API Requests

Collapse
 
simpgeek profile image
Nigel Kirby • Edited

One of the reasons to use the async/await syntax is to avoid the nested code that comes from .then() and .catch(). The fetchData function can simply become:

const fetchData = async () => {
    res.locals.data = await fetchApi(endpoint)
    next()
}

Keep in mind that this could result in an unhandled promise rejection (this was true before as well.) To actually handle errors from that fetchApi interaction just wrap a try catch:

const fetchData = async () => {
    try{
        res.locals.data = await fetchApi(endpoint)
        next()
    } catch (err) {
        next(err)
    }
}
Collapse
 
whoisryosuke profile image
Ryosuke

Good tips šŸ”„ I def need to use more try/catch in my workflow šŸ‘