UNPKG

2.58 kBJavaScriptView Raw
1'use strict'
2
3//This file contains then/promise specific extensions to the core promise API
4
5var Promise = require('./core.js')
6var nextTick = require('./lib/next-tick')
7
8module.exports = Promise
9
10/* Static Functions */
11
12Promise.from = function (value) {
13 if (value instanceof Promise) return value
14 return new Promise(function (resolve) { resolve(value) })
15}
16Promise.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}
29Promise.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
47Promise.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/* Prototype Methods */
77
78Promise.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}
86Promise.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