UNPKG

1.78 kBJavaScriptView Raw
1'use strict';
2
3// This file contains then/promise specific extensions that are only useful
4// for node.js interop
5
6var Promise = require('./core.js');
7
8
9module.exports = Promise;
10
11/* Static Functions */
12
13Promise.denodeify = function (fn, argumentCount) {
14 argumentCount = argumentCount || Infinity;
15 return function () {
16 var self = this;
17 var args = Array.prototype.slice.call(arguments);
18 return new Promise(function (resolve, reject) {
19 while (args.length && args.length > argumentCount) {
20 args.pop();
21 }
22 args.push(function (err, res) {
23 if (err) reject(err);
24 else resolve(res);
25 })
26 var res = fn.apply(self, args);
27 if (res &&
28 (
29 typeof res === 'object' ||
30 typeof res === 'function'
31 ) &&
32 typeof res.then === 'function'
33 ) {
34 resolve(res);
35 }
36 })
37 }
38}
39Promise.nodeify = function (fn) {
40 return function () {
41 var args = Array.prototype.slice.call(arguments);
42 var callback =
43 typeof args[args.length - 1] === 'function' ? args.pop() : null;
44 var ctx = this;
45 try {
46 return fn.apply(this, arguments).nodeify(callback, ctx);
47 } catch (ex) {
48 if (callback === null || typeof callback == 'undefined') {
49 return new Promise(function (resolve, reject) {
50 reject(ex);
51 });
52 } else {
53 setImmediate(function () {
54 callback.call(ctx, ex);
55 })
56 }
57 }
58 }
59}
60
61Promise.prototype.nodeify = function (callback, ctx) {
62 if (typeof callback != 'function') return this;
63
64 this.then(function (value) {
65 setImmediate(function () {
66 callback.call(ctx, null, value);
67 });
68 }, function (err) {
69 setImmediate(function () {
70 callback.call(ctx, err);
71 });
72 });
73}