Skip to content

Commit

Permalink
add the spawn function for ES6 generators
Browse files Browse the repository at this point in the history
  • Loading branch information
jlongster committed May 31, 2013
1 parent 4e2ae5d commit 6a34b92
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
27 changes: 27 additions & 0 deletions examples/async-generators/3-spawn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
var Q = require('../../q');

function delay(millis, answer) {
const deferredResult = Q.defer();
setTimeout(function() {
deferredResult.resolve(answer);
}, millis);
return deferredResult.promise;
}

function foo() {
return delay(1000, 5);
}

function bar() {
return delay(1000, 10);
}

Q.spawn(function*() {
var x = yield foo();
console.log(x);

var y = yield bar();
console.log(y);

console.log('result', x + y);
});
12 changes: 12 additions & 0 deletions q.js
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,18 @@ function async(makeGenerator) {
};
}

/**
* The spawn function is a small wrapper around async that immediately
* calls the generator and also ends the promise chain, so that any
* unhandled errors are thrown instead of forwarded to the error
* handler. This is useful because it's extremely common to run
* generators at the top-level to work with libraries.
*/
Q.spawn = spawn;
function spawn(makeGenerator) {
Q.done(Q.async(makeGenerator)());
}

// FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
/**
* Throws a ReturnValue exception to stop an asynchronous generator.
Expand Down

0 comments on commit 6a34b92

Please sign in to comment.