Skip to content

Instantly share code, notes, and snippets.

@brickpop
Last active December 9, 2016 18:29
Show Gist options
  • Select an option

  • Save brickpop/7e60f5f17a6034e8be46fbd9af32f90b to your computer and use it in GitHub Desktop.

Select an option

Save brickpop/7e60f5f17a6034e8be46fbd9af32f90b to your computer and use it in GitHub Desktop.
Coroutines example
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