Last active
November 30, 2015 17:54
-
-
Save HallM/57381b9a68b0f087539a to your computer and use it in GitHub Desktop.
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
import Bluebird from 'bluebird'; | |
// assume express, promise-ready ORM (Sequelize, Bookshelf, Mongoose) | |
function wrap(genFn) { | |
var cr = Bluebird.coroutine(genFn); | |
return function (req, res, next) { | |
cr(req, res, next).catch(next); | |
} | |
} | |
app.get('/', wrap(function*(req, res) { | |
if (!isRequestValid(req)) { | |
// throws will be sent to the err handler | |
// Many error types can be made for all the status codes to simplify code | |
throw new BadRequestError('The request was invalid!'); | |
} | |
// if there's an error with yield fail, it'll be passed to the err handler | |
var items = yield Items.find({}).exec(); | |
// if you have extra stuff to fetch that are determined by flags | |
// and the extra stuff can be fetched in parallel. | |
var extraFetchers = []; | |
if (needStuff1) { | |
extraFetchers.push(Stuff1.find({}).exec()); | |
} else { | |
// this makes sure that the index of stuff1 and stuff2 is always the same | |
extraFetchers.push(Promise.resolve(null)); | |
} | |
if (needStuff2) { | |
extraFetchers.push(Stuff2.find({}).exec()); | |
} else { | |
extraFetchers.push(Promise.resolve(null)); | |
} | |
// if we have array destructuring, it's super handy | |
var [stuff1, stuff2] = yield extraFetchers; | |
// if not, var stuffs = yield extraFetchers; | |
res.locals.items = items; | |
res.locals.stuff1 = stuff1; // could do stuffs[0] if we didn't have array destructuring | |
res.locals.stuff2 = stuff2; // and stuffs[1] | |
res.render('mypage'); | |
}); | |
app.use(function(err, req, res, next) { | |
// handle error | |
res.locals.err = err; | |
res.render('errpage'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment