Created
September 16, 2017 09:02
-
-
Save jamesseanwright/ec2172c7ecf8410542dd70cc2072332b to your computer and use it in GitHub Desktop.
Handling Promise rejection within Express routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const fetch = require('node-fetch'); | |
const express = require('express'); | |
const router = express.Router(); | |
/* This function returns an inner function(i.e. a higher-order | |
* function) that will be invoked by Express when a particular | |
* path is request. This inner function will invoke the wrapped | |
* handler, and invoke Express' next function if the returned | |
* Promise is rejected. */ | |
function createPromiseRoute(route) { | |
return (req, res, next) => route(req, res).catch(next); | |
} | |
function myRoute(req, res) { | |
return fetch('https://some-api') | |
.then(r => r.json()) | |
.then(r => res.json(r)); | |
} | |
router.get('/data', createPromiseRoute(myRoute)); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment