Skip to content

Instantly share code, notes, and snippets.

@learncodeacademy
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save learncodeacademy/812bdedba45268164976 to your computer and use it in GitHub Desktop.
Save learncodeacademy/812bdedba45268164976 to your computer and use it in GitHub Desktop.
Async Generator Tests

###Doing Express.js Async With Generators###

Using Co library, run generators as responses by wrapping Co and adding an extra function to handle errors

  • Because Co always runs the last argument as a callback...so it would always runs next() by default
  • This function only runs next if there's an error
//assign this to the Co module somewhere in application bootstrapping, 
//so you can do var ce = require('co').coExpress in each router file
co.coExpress = (generator) => {
  return (...args) => {
    co(generator).apply(...args, e => { if (e) args.pop()(e); }); //run next(e) if there are errors
  };
}

###Now for some examples!###

3 Series Requests

router.get('/series', ce(function* (req, res, next) {
  res.status(200).send({
    degrees: JSON.parse(yield get('http://myapi.com/degrees')),
    categories: JSON.parse(yield get('http://myapi.com/categories')),
    subjects: JSON.parse(yield get('http://myapi.com/subjects'))
  });
}));

3 Parallel Requests

router.get('/parallel', ce(function* (req, res, next) {
  var data = yield {
    degrees: get('http://myapi.com/degrees'),
    categories: get('http://myapi.com/categories'),
    subjects: get('http://myapi.com/subjects')
  };
  res.status(200).send({
    degrees: JSON.parse(data.degrees),
    categories: JSON.parse(data.categories),
    subjects: JSON.parse(data.subjects)
  });
}));

Parallel Requests with alternate destructured syntax

router.get('/parallel2', ce(function* (req, res, next) {
  var [degrees, categories] = yield [
    get('http://myapi.com/degrees'),
    get('http://myapi.com/categories'),
  ];

  res.status(200).send({
    degrees: JSON.parse(degrees),
    categories: JSON.parse(categories)
  });
}));

Complex example: 2 Parallel actions, the 2nd action is actually 3 series actions

router.get('/parallel3', ce(function* (req, res, next) {
  //async operation one
  var first = get('first', 2000); //start this, but don't yield it
  //arync opearation two - run these in series
  var second = yield get('second', 1000); //yield pauses execution
  var third = yield get('third', 1000);
  var fourth = yield get('fourth', 1000);

  res.status(200).send({
    first: yield first, //yield first now, so we don't block anything else
    second: second,
    third: third,
    fourth: fourth
  });
  //MAN that was WAY too easy!
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment