Last active
December 9, 2016 18:29
-
-
Save brickpop/7e60f5f17a6034e8be46fbd9af32f90b to your computer and use it in GitHub Desktop.
Coroutines example
This file contains hidden or 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
| var Promise = require('bluebird'); | |
| module.exports = function wrap(genFn) { | |
| const promisedFunc = Promise.coroutine(genFn); | |
| return (req, res, next) => { | |
| promisedFunc(req, res, next).catch(next); | |
| } | |
| }; | |
| // ------------------------------------------------------ | |
| var express = require('express'); | |
| var router = express.Router(); | |
| router.get('/items/:id', [ wrap(getItem) ]); | |
| // Express error handling | |
| router.use(function(err, req, res, next){ | |
| if(!err) return res.send(''); | |
| res.status(500).send({error: err.message || err}); | |
| }); | |
| // Coroutine - handler | |
| function* getItem(req, res){ | |
| const data = yield fetch('http://url/item.txt'); | |
| if(!data) return res.status(404).send('not found'); | |
| res.send(data); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment