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