Skip to content

Instantly share code, notes, and snippets.

@tikurahul
Created November 13, 2013 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tikurahul/7457672 to your computer and use it in GitHub Desktop.
Save tikurahul/7457672 to your computer and use it in GitHub Desktop.
Flow control with Generators
Please correct me if I am making incorrect assumptions:
The way everything works is
async(function *() {
// generator expression
// returns multiple promises
var x = yield $.ajax('http://x....');
var y = yield $.ajax('http://y....');
yield {'x': x, 'y': y }
})
The generator expression returns a promise at the end of every yeild step. We can set state on the generator using the next() with arguments.
The only other usecase - which this does not cover is doing multiple things at the 'same' time i.e creating a barrier where we determine that the only places where x, y are being used after the second yeild statement. Hence its safe to execute the second yeild statement before the resolve / reject of the first promise ? Am i right ?
@ForbesLindesay
Copy link

Kind of, it would be better to say that a generator expression 'yields' multiple promises. You should then change the last yield keyword to a return and that way it would yield two promises and return an object.

You are correct that it doesn't do parallelisation implicitly. What you could do is yield on usage rather than yield on promise creation, e.g.

var fn = async(function *() {
  // generator expression
  // yields multiple promises then returns an object

  var x = $.ajax('http://x....');
  var y = $.ajax('http://y....');
  return {'x': yield x, 'y': yield y }
})
fn().done(function (result) {
  // result is {x, y} with values not promises
});

Doing this would largely automate the parallelisation for you, at the cost of sometimes having extra yields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment