3 // This file contains then/promise specific extensions that are only useful
6 var Promise = require('./core.js');
7 var asap = require('asap');
9 module.exports = Promise;
11 /* Static Functions */
13 Promise.denodeify = function (fn, argumentCount) {
15 typeof argumentCount === 'number' && argumentCount !== Infinity
17 return denodeifyWithCount(fn, argumentCount);
19 return denodeifyWithoutCount(fn);
24 'function (err, res) {' +
25 'if (err) { rj(err); } else { rs(res); }' +
28 function denodeifyWithCount(fn, argumentCount) {
30 for (var i = 0; i < argumentCount; i++) {
34 'return function (' + args.join(',') + ') {',
36 'return new Promise(function (rs, rj) {',
38 ['self'].concat(args).concat([callbackFn]).join(','),
41 '(typeof res === "object" || typeof res === "function") &&',
42 'typeof res.then === "function"',
47 return Function(['Promise', 'fn'], body)(Promise, fn);
49 function denodeifyWithoutCount(fn) {
50 var fnLength = Math.max(fn.length - 1, 3);
52 for (var i = 0; i < fnLength; i++) {
56 'return function (' + args.join(',') + ') {',
59 'var argLength = arguments.length;',
60 'if (arguments.length > ' + fnLength + ') {',
61 'args = new Array(arguments.length + 1);',
62 'for (var i = 0; i < arguments.length; i++) {',
63 'args[i] = arguments[i];',
66 'return new Promise(function (rs, rj) {',
67 'var cb = ' + callbackFn + ';',
69 'switch (argLength) {',
70 args.concat(['extra']).map(function (_, index) {
72 'case ' + (index) + ':' +
73 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' +
78 'args[argLength] = cb;',
79 'res = fn.apply(self, args);',
83 '(typeof res === "object" || typeof res === "function") &&',
84 'typeof res.then === "function"',
96 Promise.nodeify = function (fn) {
98 var args = Array.prototype.slice.call(arguments);
100 typeof args[args.length - 1] === 'function' ? args.pop() : null;
103 return fn.apply(this, arguments).nodeify(callback, ctx);
105 if (callback === null || typeof callback == 'undefined') {
106 return new Promise(function (resolve, reject) {
111 callback.call(ctx, ex);
118 Promise.prototype.nodeify = function (callback, ctx) {
119 if (typeof callback != 'function') return this;
121 this.then(function (value) {
123 callback.call(ctx, null, value);
127 callback.call(ctx, err);