Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

shim in q.execute for promised-io compatability

  • Loading branch information...
commit 1b48d6f5cc5fae8e63217fc48896872afb34075e 1 parent 1568d4e
@nrstott authored
Showing with 33 additions and 2 deletions.
  1. +33 −2 lib/q.js
View
35 lib/q.js
@@ -1,4 +1,5 @@
-var q = require('q');
+var q = require('q')
+ , slice = Array.prototype.slice;
/**
* Wraps a Node.JS style asynchronous function `function(err, result) {}`
@@ -12,7 +13,7 @@ var q = require('q');
q.promisify = function(nodeAsyncFn, context) {
return function() {
var defer = q.defer()
- , args = Array.prototype.slice.call(arguments);
+ , args = slice.call(arguments);
args.push(function(err, val) {
if (err !== null) {
@@ -28,6 +29,36 @@ q.promisify = function(nodeAsyncFn, context) {
};
};
+if (!q.execute) {
+ /**
+ * Runs a Node.JS style asynchronous function `function(err, result) {}`, but returns a Promise instead.
+ * @param {Function} Node.JS compatible async function which takes a callback as its last argument
+ * @returns {Promise} A promise for the return value from the callback from the function
+ */
+ q.execute = function(asyncFunction){
+ var defer = q.defer()
+ , args = slice.call(arguments, 1);
+
+ args.push(function(err, result){
+ if(err !== null) {
+ defer.reject(err);
+ }
+ else {
+ if(arguments.length > 2){
+ // Return an array if multiple success values.
+ Array.prototype.shift.call(arguments, 1);
+ defer.resolve(arguments);
+ }
+ else{
+ defer.resolve(result);
+ }
+ }
+ });
+ asyncFunction.apply(this, args);
+ return defer.promise;
+ };
+}
+
if (!q.resolve) {
q.resolve = function(val) {
var deferred = q.defer();
Please sign in to comment.
Something went wrong with that request. Please try again.