1 | 'use strict'
|
2 |
|
3 |
|
4 |
|
5 | var Promise = require('./core.js')
|
6 | var nextTick = require('./lib/next-tick')
|
7 |
|
8 | module.exports = Promise
|
9 |
|
10 |
|
11 |
|
12 | Promise.from = function (value) {
|
13 | if (value instanceof Promise) return value
|
14 | return new Promise(function (resolve) { resolve(value) })
|
15 | }
|
16 | Promise.denodeify = function (fn) {
|
17 | return function () {
|
18 | var self = this
|
19 | var args = Array.prototype.slice.call(arguments)
|
20 | return new Promise(function (resolve, reject) {
|
21 | args.push(function (err, res) {
|
22 | if (err) reject(err)
|
23 | else resolve(res)
|
24 | })
|
25 | fn.apply(self, args)
|
26 | })
|
27 | }
|
28 | }
|
29 | Promise.nodeify = function (fn) {
|
30 | return function () {
|
31 | var args = Array.prototype.slice.call(arguments)
|
32 | var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
|
33 | try {
|
34 | return fn.apply(this, arguments).nodeify(callback)
|
35 | } catch (ex) {
|
36 | if (callback == null) {
|
37 | return new Promise(function (resolve, reject) { reject(ex) })
|
38 | } else {
|
39 | nextTick(function () {
|
40 | callback(ex)
|
41 | })
|
42 | }
|
43 | }
|
44 | }
|
45 | }
|
46 |
|
47 | Promise.all = function () {
|
48 | var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments)
|
49 |
|
50 | return new Promise(function (resolve, reject) {
|
51 | if (args.length === 0) return resolve([])
|
52 | var remaining = args.length
|
53 | function res(i, val) {
|
54 | try {
|
55 | if (val && (typeof val === 'object' || typeof val === 'function')) {
|
56 | var then = val.then
|
57 | if (typeof then === 'function') {
|
58 | then.call(val, function (val) { res(i, val) }, reject)
|
59 | return
|
60 | }
|
61 | }
|
62 | args[i] = val
|
63 | if (--remaining === 0) {
|
64 | resolve(args);
|
65 | }
|
66 | } catch (ex) {
|
67 | reject(ex)
|
68 | }
|
69 | }
|
70 | for (var i = 0; i < args.length; i++) {
|
71 | res(i, args[i])
|
72 | }
|
73 | })
|
74 | }
|
75 |
|
76 |
|
77 |
|
78 | Promise.prototype.done = function (onFulfilled, onRejected) {
|
79 | var self = arguments.length ? this.then.apply(this, arguments) : this
|
80 | self.then(null, function (err) {
|
81 | nextTick(function () {
|
82 | throw err
|
83 | })
|
84 | })
|
85 | }
|
86 | Promise.prototype.nodeify = function (callback) {
|
87 | if (callback == null) return this
|
88 |
|
89 | this.then(function (value) {
|
90 | nextTick(function () {
|
91 | callback(null, value)
|
92 | })
|
93 | }, function (err) {
|
94 | nextTick(function () {
|
95 | callback(err)
|
96 | })
|
97 | })
|
98 | } |
\ | No newline at end of file |