-
Notifications
You must be signed in to change notification settings - Fork 8
/
promise.mjs
222 lines (197 loc) · 5.06 KB
/
promise.mjs
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
class NPromise extends Promise {
delay(ms = 0) {
return this.then((value) => NPromise.delay(ms, value));
}
map(fn, options) {
return this.then((arr) => NPromise.map(arr, fn, options));
}
mapSeries(fn) {
return this.then((arr) => NPromise.mapSeries(arr, fn));
}
each(fn) {
return this.then((arr) => NPromise.each(arr, fn));
}
timeout(ms = 0, msg) {
const timeoutPromise = new NPromise((_, reject) => {
setTimeout(
() =>
reject(
msg instanceof Error ? msg : new Error(msg || "Request timed out"),
),
ms,
);
});
return NPromise.race([this, timeoutPromise]);
}
tap(fn) {
return new NPromise((resolve, reject) => {
this.then(async (val) => {
await fn(val);
resolve(val);
}).catch(reject);
});
}
all() {
return this.then((arr) => NPromise.all(arr));
}
spread(fn) {
return this.then(function () {
if (typeof fn !== "function") {
throw new TypeError(
`Promise.spread requires function, but got ${typeof fn}`,
);
}
return fn.apply(null, arguments[0]);
});
}
reduce(fn, initialValue) {
return NPromise.reduce(this, fn, initialValue);
}
asCallback(callback) {
if (typeof callback !== "function") {
return this;
}
this.then(
(value) => {
queueMicrotask(() => {
try {
callback(null, value);
} catch (err) {
queueMicrotask(() => {
throw err;
});
}
});
},
(error) => {
queueMicrotask(() => {
try {
if (!error) {
error = new Error("Promise rejected without a reason", {
cause: error,
});
}
callback(error);
} catch (err) {
queueMicrotask(() => {
throw err;
});
}
});
},
);
return this;
}
}
NPromise.delay = function delay(ms = 0, value) {
return new NPromise((resolve) => setTimeout(() => resolve(value), ms));
};
NPromise.try = function (fn) {
return new NPromise(function (resolve, reject) {
if (typeof fn !== "function") {
reject(
new TypeError(`Promise.try requires function, but got ${typeof fn}`),
);
}
resolve(fn());
});
};
// TODO refactor with Symbol.Iterable
NPromise.each = async function each(arr, fn) {
if (!Array.isArray(arr)) {
throw new TypeError(`Promise.each requires array, but got ${typeof arr}`);
}
const values = [];
for (let i = 0; i < arr.length; i++) {
const val = await NPromise.resolve(arr[i]);
values.push(val);
await fn(val, i, arr.length);
}
return values;
};
// TODO refactor with Symbol.Iterable
NPromise.mapSeries = function mapSeries(arr, fn) {
if (!Array.isArray(arr)) {
throw new TypeError(
`Promise.mapSeries requires array, but got ${typeof arr}`,
);
}
return new NPromise(async (resolve, reject) => {
const results = [];
for (let i = 0; i < arr.length; i++) {
try {
const val = await NPromise.resolve(arr[i]);
results[i] = await fn(val, i, arr.length);
} catch (err) {
reject(err);
}
}
resolve(results);
});
};
NPromise.map = function map(iterable, fn, options) {
options = options || {};
let concurrency = options.concurrency || Infinity;
let index = 0;
const results = [];
if ("then" in iterable) {
return iterable.then((arr) => {
if (!Array.isArray(arr)) {
throw new TypeError(
`Promise.map requires array, but got ${typeof arr}`,
);
}
return NPromise.map(arr, fn, options);
});
}
const iterator = iterable[Symbol.iterator]();
const promises = [];
while (concurrency-- > 0) {
const promise = wrappedMapper();
if (promise) promises.push(promise);
else break;
}
return NPromise.all(promises).then(() => results);
function wrappedMapper() {
const next = iterator.next();
if (next.done) return null;
const i = index++;
return Promise.resolve(next.value).then(async (unwrapped) => {
const mapped = await fn(unwrapped, i);
results[i] = mapped;
return wrappedMapper(mapped);
});
}
};
NPromise.defer = function defer() {
let resolve, reject;
const promise = new NPromise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return {
resolve,
reject,
promise,
};
};
NPromise.reduce = async function reduce(iterable, fn, initialValue) {
if (typeof fn !== "function") {
throw new TypeError(
`Promise.reduce requires function, but got ${typeof fn}`,
);
}
return NPromise.all(await iterable).then(async (list) => {
const iterator = list[Symbol.iterator]();
let ret = await initialValue;
let item = null;
let idx = -1;
while (((item = iterator.next()), !item.done)) {
ret = ++idx === 0 && ret === undefined
? await item.value
: await fn(ret, item.value, idx, list.length);
}
return ret;
});
};
export default NPromise;