Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add new demo, fix error delegation

  • Loading branch information...
commit f477792a16fad628d34ac557f3fae61e48ebbea5 1 parent 323b4d9
Adam Crabtree authored
326 README.markdown
View
@@ -1,207 +1,155 @@
-# Step
-
-A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless.
-
-## How to install
-
-Simply copy or link the lib/step.js file into your `$HOME/.node_libraries` folder.
-
-## How to use
-
-The step library exports a single function I call `Step`. It accepts any number of functions as arguments and runs them in serial order using the passed in `this` context as the callback to the next step.
-
- Step(
- function readSelf() {
- fs.readFile(__filename, this);
- },
- function capitalize(err, text) {
- if (err) throw err;
- return text.toUpperCase();
- },
- function showIt(err, newText) {
- if (err) throw err;
- console.log(newText);
- }
- );
-
-Notice that we pass in `this` as the callback to `fs.readFile`. When the file read completes, step will send the result as the arguments to the next function in the chain. Then in the `capitalize` function we're doing synchronous work so we can simple return the new value and Step will route it as if we called the callback.
-
-The first parameter is reserved for errors since this is the node standard. Also any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down.
-
-Also there is support for parallel actions:
-
- Step(
- // Loads two files in parallel
- function loadStuff() {
- fs.readFile(__filename, this.parallel());
- fs.readFile("/etc/passwd", this.parallel());
- },
- // Show the result when done
- function showStuff(err, code, users) {
- if (err) throw err;
- sys.puts(code);
- sys.puts(users);
- }
- )
-
-Here we pass `this.parallel()` instead of `this` as the callback. It internally keeps track of the number of callbacks issued and preserves their order then giving the result to the next step after all have finished. If there is an error in any of the parallel actions, it will be passed as the first argument to the next step.
-
-Also you can use group with a dynamic number of common tasks.
-
- Step(
- function readDir() {
- fs.readdir(__dirname, this);
- },
- function readFiles(err, results) {
- if (err) throw err;
- // Create a new group
- var group = this.group();
- results.forEach(function (filename) {
- if (/\.js$/.test(filename)) {
- fs.readFile(__dirname + "/" + filename, 'utf8', group());
- }
- });
- },
- function showAll(err , files) {
- if (err) throw err;
- sys.p(files);
- }
- );
-
-*Note* that we both call `this.group()` and `group()`. The first reserves a slot in the parameters of the next step, then calling `group()` generates the individual callbacks and increments the internal counter.
-
-
-
-
-
-
-
-
-
-
-
-
-
+# Sexy
+A control-flow library for making sequential asynchronous in a synchronous style format using ECMAScript 5 Proxies and Tim Caswell's (@creationix) Step, http://github.com/creationix/step .
+## Alpha Alert
+This is an alpha release of Sexy. Please submit all bugs to http://github.com/CrabDude/sexy/issues
-# Ship
-
-Ship lets you write less callbacks.
-
-## Introduction
-
-The convention in node.js is that an asynchronous library function takes a callback as its last parameter.
-When it finishes, it invokes this callback - the first parameter is the error, and the rest are the data.
-
-This is powerful:
- fs.readFile('/etc/passwd', function(err, data) {
- if(err) throw err;
- console.log(data);
- });
-
-But quickly becomes verbose and tangled:
- fs.readFile('/etc/passwd', function(err, data) [
- if(err) throw err;
- fs.writeFile('/etc/passwd.bak', data, function(err) {
- if(err throw err);
- console.log("It's saved");
- }
- }
-
-What about this:
- var pfs = ship(fs);
- pfs.writeFile('/etc/passwd.bak', pfs.readFile('/etc/passwd'));
- pfs.end(function(err) {
- if(err) throw err;
- console.log("It's saved");
- });
-
-Another example: method chaining.
-
-Before:
- var thing = new Thing();
- thing.asyncOne(function(err, data) {
- if(err) throw err;
- data.asyncTwo(function(err, result) {
- if(err) throw err;
- console.log("Success: "+result);
- }
- }
-
-After:
- var pthing = ship(new Thing());
- thing.asyncOne().asyncTwo().end(function(err, result) {
- if(err) throw err;
- console.log("Success: result");
- });
-
-## How it works
-
-The things returned by ship, and subsequent method calls, are basically promises.
-
-Things will be done to the actual objects in the same order as you do things to the promises.
-
-If a function invoked on a promise takes another promise as a parameter, the value will be passed instead.
-
-## API
-
-### ship(obj)
-
-Returns: a promise for obj
-
-### promise.foo(args...)
-
-Adds promise.foo(args...) to the queue as an asynchronous call. Args can be promises (from the same queue), or any other values.
-
-The actual call made will be <promise>.foo(<args...>, cb) where <promise> is the value of promise, <args> is args with all promises evaluated, and cb is a node-style callback.
-
-If <promise>.foo is defined but is not a function, it will be treated as a simple accessor that returns that value.
-
-If you pass an error to cb, further execution will be skipped and the error will be handled.
-
-Returns: a promise for the first return value (i.e. the second argument passed to cb).
-
-### promise.foo$(args...)
-
-Adds promise.foo(args...) to the queue as a synchronous call. Args can be promises (from the same queue), or any other values.
-
-The actual call made will be <promise>.foo(<args...>) where <promise> is the value of promise, and <args> is args with all promises evaluated.
-
-If <promise>.foo is defined but is not a function, it will be treated as a simple accessor that returns that value.
+## How to install
-If the function throws an error, further execution will be skipped and the error will be handled.
+ npm install sexy
-Returns: a promise for the return value of the call.
+Or copy or link the lib/sexy.js file into your `$HOME/.node_libraries` folder.
-### promise.deliver(func)
+## How to use
-Registers a listener, when the value(s) for the promise is available, func will be called with the values as arguments.
+Sexy utilizes ECMAScript 5 Proxies to allow nested asynchronous code to be written in a synchronous style format.
+
+Sexy exports a single function I call `$xy`. $xy() initializes a sequence and 2 arguments: the initial object to wrap and an onError callback.
+
+ $xy(fs,function(e) {if (e) throw e;});
+
+Function callbacks are handled automatically by Sexy and the results from the previous step are passed to the next.
+
+ $xy(fs).readdir(__dirname)(function(filenames) {
+ // do something
+ });
+
+Additionally, any errors generated by a step in the sequence will be passed to the onError callback from initialization.
+
+The resulting $xy instance can then be used to write asynchronous code in a synchronous format.
+
+ $xy(fs,function(e) {
+ // log error
+ console.log('ERROR');
+ if (e) throw e;
+ }).readdir(__dirname)(function(filenames) {
+ console.log(SERIOUSLY.DOESNOTEXIST);
+ });
+
+Here is an example that outputs the contents of all "*.js" files in a directory:
+
+Standard Node.js code:
+
+ $xy(fs,function(e) {if (e) throw e;})
+ .readdir(__dirname)
+ .forEach(function(filename) {
+ if (/\.js$/.test(filename)) {
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ })
+ (console.log)
+ (function() {console.log('hello world');});
+
+Step equivalent:
+
+ Step(
+ function readdir() {
+ fs.readdir(__dirname, this);
+ },
+ function readFiles(err, results) {
+ if (err) throw err;
+ results.forEach(function (filename) {
+ if (/\.js$/.test(filename)) {
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ });
+ },
+ function showAll(err , file1, file2, file3) {
+ if (err) throw err;
+ console.log(arguments);
+ },
+ function() {
+ if (err) throw err;
+ console.log('hello world');
+ }
+ );
+
+AN ATTEMPT at the standard Node.js equivalent:
+
+ // This could certainly be written better
+ // Step provides numerous wrapping features that make writing an equivalent example cumbersome like wrapping your callbacks in try.. catch blocks.
+
+ fs.readdir(__dirname, function(err, results) {
+ if (err) throw err;
+ function callback(err, file) {
+ if (err) throw err;
+ function callback2() {
+ if (err) throw err;
+ console.log('hello world');
+ }
+ files.push(file);
+ if (++counter != total) {
+ return;
+ }
+ console.log(files);
+ }
+ var files = [], counter = 0, total = 0;
+ results.forEach(function (filename) {
+ if (/\.js$/.test(filename)) {
+ total++;
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ });
+ });
+
+Note that all callbacks can utilize the Step API as Sexy wraps all callbacks in a Step call. As a result, utilizing this and this.parallel and return values, BUT NOT this.group YET, all function as they do in Step. Please refer to the Step README for the Step documentation: http://github.com/creationix/step .
+
+A few key differences in Sexy are that the original binding for `this` is available at `this.that` in the callback. Support for `this.that` at the moment is a little buggy.
+
+Sexy assumes that a function call on a non-function result is a sequential call outside of the current context. Two examples of this functionality are the last two lines of the Sexy example.
+
+ $xy(fs,function(e) {if (e) throw e;})
+ ...
+ (console.log)
+ (function() {console.log('hello world');});
+
+The first "console.log" is passed the resulting arguments from the previous callback, in this case the contents of the files. In the second, an anonymous function is used to execute an arbitrary final command once the sequence is complete.
+
+In the event that the previous function call, beit from an object or an anonymous sequential call, returns a function, to call that function you must pass an undefined value or the $xy.undef convenience value as the first argument. This is one of a few gray areas as mentioned below. Please submit API recommendations as a feature request to http://github.com/CrabDude/sexy/issues .
+
+ var objectX = {
+ returnArbitraryFunction: function () {
+ // do something fancy
+ return function() {
+ console.log('arbitrary function');
+ };
+ }
+ }
+
+ // Execute next function sequentially
+ $xy(objectX).returnArbitraryFunction()(function() {
+ // this WILL NOT call the function returned by objectX.returnArbitraryFunction()
+ });
+
+ // Call returned function
+ $xy(objectX).returnArbitraryFunction()($xy.undef,function() {
+ // this WILL call the function returned by objectX.returnArbitraryFunction()
+ });
+
+
+
+## API Gray Areas / Ambiguity
+
+Please submit API recommendations as a feature request to http://github.com/CrabDude/sexy/issues
-Func will not be called if the promise doesn't get a value because an earlier invocation raises an error.
-Returns: promise (for chaining)
-### promise.end(cb)
-Starts the queue. This must only be done once per queue (i.e per call to ship()).
-Upon completion, cb will be called. If there was an error, it will be the first argument.
-Otherwise the first argument is null, and the second argument is the value of this promise.
-Returns: undefined.
-## Limitations
-This works:
- var pthing = ship(new Thing());
- var derivedValue = pthing.getValue();
- pthing.doSomething(derivedValue); // passes the actual value, not the promise
-This can never work:
- console.log(derivedValue); // passes the promise
-This doesn't either, but maybe one day:
- var pconsole = ship(console); // each call to ship() creates an independent queue
- pconsole.log(derivedValue); // you can't mix promises from different queues
18 lib/sexy.js
View
@@ -25,11 +25,18 @@ SOFTWARE.
var EventEmitter = require('events').EventEmitter,
Proxy = require('node-proxy'),
Step = require('step'),
+ fs = require('fs'),
misc = {
debug: false,
log: function () {
if (misc.debug) {
- console.log.apply(console,arguments);
+ for (var i=0,l=arguments.length; i<l; ++i) {
+ if (arguments[i] === fs)
+ Array.prototype.splice.call(arguments,i,1);
+ }
+ if (arguments) {
+ console.log.apply(console,arguments);
+ }
}
},
bind: function (context, fn){
@@ -178,15 +185,16 @@ Sexy.prototype = misc.extend(Sexy.prototype, {
misc.log('wrap',arguments);
var self = this;
return function() {
- misc.log('wrap callback',last,fn.toString(),arguments);
+ misc.log('wrap callback',fn.toString(),shouldThrow,last,arguments);
var args = Array.prototype.slice.call(arguments),
err = args[0];
- if (err && typeof err == 'object' && err.constructor === TypeError) {
+ if (err instanceof Error) {
misc.log('ERROR!',err,shouldThrow,fn);
this.err = err;
if (shouldThrow) {
throw err;
} else {
+ misc.log('Calling onError',self.onError.toString(),err);
self.onError(err);
}
return;
@@ -233,11 +241,11 @@ function SexyProxy(context,onError) {
var args = arguments;
if (typeof self.sexy.context != 'function'
|| (typeof args[0] == 'function' && self.sexy.previous != self.sexy.type.value)) {
- misc.log('proxy call - sync');
+ misc.log('proxy call - sync','toString' in args[0] && args[0].toString());
self.sexy.enqueue([2,args]);
} else {
misc.log('proxy call - async');
- if (typeof args[0] == 'undefined' && typeof args[1] == 'function') {
+ if (args[0] === self.sexy.undef && typeof args[1] == 'function') {
args = Array.prorototype.slice.call(args,1);
}
self.sexy.enqueue([1,args]);
2  package.json
View
@@ -1,7 +1,7 @@
{
"name" : "sexy",
"description" : "Sequential Proxy for writing Asynchronous with ECMAScript 5 Proxies",
- "version" : "0.0.1",
+ "version" : "0.0.2",
"homepage": "http://github.com/CrabDude/sexy",
"repository": {
"type" : "git",
78 test/demo.js
View
@@ -1,21 +1,61 @@
var $xy = require('../lib/sexy'),
- fs = require('fs'),
- util = require('util');
-
-var proxy = $xy(fs,function(e) {
- console.log('ERROR! ERROR! ERROR! ERROR! ERROR!');
- if (e) throw e;
-}).readdir(__dirname)(function(files) {
- console.log(files);
- return files;
-}).forEach(function(filename) {
-// var self = this.that; <-- Available, but no meaning in Array.prototype.forEach
- if (/\.js$/.test(filename)) {
- fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ fs = require('fs');
+
+$xy(fs,function(e) {if (e) throw e;})
+ .readdir(__dirname)
+ .forEach(function(filename) {
+ if (/\.js$/.test(filename)) {
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ })
+ (console.log);
+
+/*
+ * COMPARE WITH THE FOLLOWING EXAMPLES
+
+
+Tim Caswell's (@creationix) Step: http://github.com/creationix/step
+
+Step(
+ function readdir() {
+ fs.readdir(__dirname, this);
+ },
+ function readFiles(err, results) {
+ if (err) throw err;
+ results.forEach(function (filename) {
+ if (/\.js$/.test(filename)) {
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ });
+ },
+ function showAll(err , file1, file2, file3) {
+ if (err) throw err;
+ console.log(arguments);
+ }
+);
+
+
+Standard asynchronous callback-based Node.js
+
+fs.readdir(__dirname, function(err, results) {
+ if (err) throw err;
+ function callback(err, file) {
+ if (err) throw err;
+ files.push(file);
+ if (++counter != total) {
+ return;
+ }
+ console.log(files);
}
-})(function() {
- util.puts(util.inspect(arguments));
- return 'hello world';
-})(function(helloWorld) {
- console.log(helloWorld);
-});
+ var files = [], counter = 0, total = 0;
+ results.forEach(function (filename) {
+ if (/\.js$/.test(filename)) {
+ total++;
+ fs.readFile(__dirname + "/" + filename, 'utf8', this.parallel());
+ }
+ });
+});
+
+*/
+
+
9 test/demo2.js
View
@@ -0,0 +1,9 @@
+var $xy = require('../lib/sexy'),
+ fs = require('fs');
+
+$xy(fs,function(e) {
+ console.log('ERROR');
+ if (e) throw e;
+ }).readdir(__dirname)(function(filenames) {
+ console.log(SERIOUSLY.DOESNOTEXIST);
+ });
Please sign in to comment.
Something went wrong with that request. Please try again.