Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

mandatory callbacks for .async(), optional for .run()

  • Loading branch information...
commit 1870e09532de980ecfd43580541dcd53981ffde9 1 parent 6f12571
@jmar777 authored
Showing with 16 additions and 16 deletions.
  1. +16 −16 lib/suspend.js
View
32 lib/suspend.js
@@ -3,16 +3,24 @@ var suspend = module.exports = function suspend(generator) {
};
suspend.async = function async(generator) {
+ // todo: generator validation
return function() {
- var args = Array.prototype.concat.apply([generator], arguments);
- // be sure to preserve `this` context
- suspend.run.apply(this, args);
+ // todo: callback validation
+ // callback is only optional if there are no args
+ var callback = arguments[arguments.length - 1],
+ args = Array.prototype.slice.call(arguments, 0, -1);
+
+ var suspender = new Suspender(generator, callback);
+ // preserve `this` context
+ suspender.start(this, args);
};
};
-suspend.run = function run(generator) {
- var suspender = new Suspender(generator);
- suspender.start(this, Array.prototype.slice.call(arguments, 1));
+suspend.run = function run(generator, callback) {
+ // todo: generator/callback validation
+ var suspender = new Suspender(generator, callback);
+ // preserve `this` context
+ suspender.start(this);
};
suspend.resume = function resumeFactory() {
@@ -62,12 +70,12 @@ var activeSuspender = null;
* Constructor function used for "wrapping" generator. Manages the state and
* interactions with a suspend-wrapped generator.
*/
-function Suspender(generator) {
+function Suspender(generator, callback) {
this.generator = generator;
// initialized in start()
this.iterator = null;
// (optionally) initialized in start()
- this.callback = null;
+ this.callback = callback;
// flag indicating whether or not the iterator has completed
this.done = false;
// flag to keep track of whether or not we were resumed synchronously.
@@ -89,14 +97,6 @@ function Suspender(generator) {
* Starts the generator and begins iteration.
*/
Suspender.prototype.start = function start(ctx, args) {
- // if we're started with exactly one more argument than is defined by the
- // generator, and the extra arg is a function, then we assume it to be a
- // callback.
- if (args.length === this.generator.length + 1)
- if (typeof args[args.length - 1] === 'function') {
- this.callback = args.pop();
- }
-
this.iterator = this.generator.apply(ctx, args);
this.nextOrThrow();
};
Please sign in to comment.
Something went wrong with that request. Please try again.