Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

adding standard node callback support #2

Open
wants to merge 1 commit into
from
Jump to file or symbol
Failed to load files and symbols.
+34 −2
Split
View
@@ -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
@@ -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');
+ }
+});