Skip to content

Commit

Permalink
Don't allow callbacks to fire till after the body is done setting up …
Browse files Browse the repository at this point in the history
…callbacks.
  • Loading branch information
creationix committed Apr 13, 2010
1 parent 08dfdc3 commit d63ae6d
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions lib/step.js 100644 → 100755
Expand Up @@ -24,7 +24,7 @@ SOFTWARE.
// modified to fit my taste and the node.JS error handling system.
function Step() {
var steps = Array.prototype.slice.call(arguments),
counter, results;
counter, results, lock;

// Define the main callback that's given as `this` to the steps.
function next() {
Expand All @@ -45,35 +45,44 @@ function Step() {

// Run the step in a try..catch block so exceptions don't get out of hand.
try {
lock = true;
var result = fn.apply(next, arguments);
} catch (e) {
// Pass any exceptions on through the next callback
next(e);
}


// If a syncronous return is used, pass it to the callback
if (result !== undefined) {
next(undefined, result);
}

lock = false;
}

// Add a special callback generator `this.parallel()` that groups stuff.
next.parallel = function () {
var i = counter;
counter++;
return function () {
function check() {
counter--;
if (counter === 0) {
// When they're all done, call the callback
next.apply(null, results);
}
}
return function () {
// Compress the error from any result to the first argument
if (arguments[0]) {
results[0] = arguments[0];
}
// Send the other results as arguments
results[i + 1] = arguments[1];
if (counter === 0) {
// When they're all done, call the callback
next.apply(null, results);
if (lock) {
process.nextTick(check);
return
}
check();
};
};

Expand Down

0 comments on commit d63ae6d

Please sign in to comment.