diff --git a/lib/step.js b/lib/step.js old mode 100644 new mode 100755 index 322dfd8..0cd33d0 --- a/lib/step.js +++ b/lib/step.js @@ -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() { @@ -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(); }; };