-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
107 lines (92 loc) · 2.18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict';
var Promise = require('promise'),
isPromise = require('is-promise');
module.exports = future;
future.shift = shift;
/**
* Creates a function that returns a promise and executes only
* after all promised arguments are resolved.
*
* @param fn
* @returns {Function}
*/
function future (fn) {
return function () {
var args = [].slice.call(arguments);
return new Promise(function (kept, broken) {
join(args).then(
function (args) {
args.push(kept);
args.push(broken);
fn.apply(null, args);
},
broken
);
});
};
}
/**
* Converts a synchronous function to work with promises
*
* @param fn
* @returns {Function}
*/
function shift (fn) {
return future(function () {
var args = [].slice.call(arguments),
broken = args.pop(),
kept = args.pop();
try {
kept(fn.apply(null, args));
} catch (reason) {
broken(reason);
}
});
}
/**
* Recursive resolves a promise util its a value
*
* @param promise
* @param kept
* @param broken
*/
function resolvePromise(promise, kept, broken) {
if (!isPromise(promise)) {
kept(promise);
} else {
promise.then(
function (value) {
resolvePromise(value, kept, broken);
},
function (value) {
resolvePromise(value, broken, broken);
}
);
}
}
/**
* Joins promises together to one promise
*
* @param promises
* @returns {Promise}
*/
function join (promises) {
var toResolve = promises.length,
resolved = [];
return new Promise(function (kept, broken) {
var check = function () {
if (toResolve === 0) {
kept(resolved);
}
};
promises.forEach(function (value, index) {
var resolve = function (value) {
toResolve--;
resolved[index] = value;
check();
};
resolvePromise(value, resolve, broken);
});
check();
});
}