From 6a34b92771d9642203b6e0593802314b81dc0bf9 Mon Sep 17 00:00:00 2001 From: James Long Date: Fri, 31 May 2013 15:52:19 -0400 Subject: [PATCH] add the spawn function for ES6 generators --- examples/async-generators/3-spawn.js | 27 +++++++++++++++++++++++++++ q.js | 12 ++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 examples/async-generators/3-spawn.js diff --git a/examples/async-generators/3-spawn.js b/examples/async-generators/3-spawn.js new file mode 100644 index 00000000..80c6f3d8 --- /dev/null +++ b/examples/async-generators/3-spawn.js @@ -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); +}); diff --git a/q.js b/q.js index 374ca851..c726ce0a 100644 --- a/q.js +++ b/q.js @@ -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.