Skip to content
Browse files

updating test to work in Node as of 0.8.15

adding method "thenNode" which takes a standard node callback (e.g. function(err, result))
  • Loading branch information...
1 parent 15c5937 commit 275381a69108daca8a5cfa331e472e7f0b6ab4f3 @thesmart thesmart committed Dec 12, 2012
Showing with 34 additions and 2 deletions.
  1. +14 −0 promise.js
  2. +20 −2 test-promise.js
View
14 promise.js
@@ -123,6 +123,20 @@ Promise.prototype.wait = function(){
return exports.wait(this);
};
+/**
+ * When promise is resolved or rejected, call a single callback in the style of Node callbacks
+ *
+ * @param {Function} nodeCallback The callback function (e.g. function(err, result))
+ * @param {*=} opt_scope Optional scope to set in the callback (default: null)
+ * @return {*}
+ */
+Promise.prototype.thenNode = function(nodeCallback, opt_scope) {
+ return this.then(
+ nodeCallback.bind(opt_scope ? opt_scope : null, null), // no err
+ nodeCallback.bind(opt_scope ? opt_scope : null) // err is first param
+ );
+};
+
Deferred.prototype = Promise.prototype;
// A deferred provides an API for creating and resolving a promise.
exports.Promise = exports.Deferred = exports.defer = defer;
View
22 test-promise.js
@@ -2,11 +2,29 @@ sys = require("sys");
var fs = require('./fs-promise');
// open a file and read it
-fs.open("fs-promise.js", process.O_RDONLY).then(function(fd){
+fs.open("fs-promise.js", 'r').then(function(fd){
return fs.read(fd, 4096);
}).then(function(args){
sys.puts(args[0]);
});
// does the same thing
-fs.readFile("fs-promise.js").addCallback(sys.puts);
+fs.readFile("fs-promise.js").addCallback(sys.puts);
+
+// does the same thing
+fs.readFile("fs-promise.js").thenNode(function(err, result) {
+ if (err) {
+ console.error(err);
+ } else {
+ console.info('thenNode result success');
+ }
+});
+
+// forced error
+fs.readFile("foobar.js").thenNode(function(err, result) {
+ if (err) {
+ console.info('thenNode err success');
+ } else {
+ console.error('err should be passed');
+ }
+});

0 comments on commit 275381a

Please sign in to comment.
Something went wrong with that request. Please try again.