-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path6-promise.js
More file actions
69 lines (56 loc) · 1.15 KB
/
6-promise.js
File metadata and controls
69 lines (56 loc) · 1.15 KB
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
'use strict';
const metasync = require('metasync');
class ArrayChain {
constructor(array) {
this._promise = Promise.resolve(array);
}
then(fn) {
return this._promise.then(fn);
}
catch(fn) {
return this._promise.catch(fn);
}
fetch(fn) {
return this.then((data) => fn(null, data)).catch((err) => fn(err));
}
_chain(performer, fn, initial) {
this._promise = this._promise.then(
(array) =>
new Promise((resolve, reject) =>
performer(
array,
fn,
(err, result) => (err ? reject(err) : resolve(result)),
initial,
),
),
);
}
map(fn) {
this._chain(metasync.map, fn);
return this;
}
filter(fn) {
this._chain(metasync.filter, fn);
return this;
}
reduce(fn, initial) {
this._chain(metasync.reduce, fn, initial);
return this;
}
each(fn) {
this._chain(metasync.each, fn);
return this;
}
series(fn) {
this._chain(metasync.series, fn);
return this;
}
find(fn) {
this._chain(metasync.find, fn);
return this;
}
}
module.exports = {
for: (array) => new ArrayChain(array),
};