-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathasync.js
81 lines (75 loc) · 1.78 KB
/
async.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
function toPromiseFactory(consumer) {
const results = [];
const resolves = [];
consumer(function(result) {
if (resolves.length > 0) {
resolves.shift()(result);
} else {
results.push(result);
}
});
return function() {
if (results.length > 0) {
return Promise.resolve(results.shift());
} else {
return new Promise(resolve => resolves.push(resolve));
}
};
}
function thunkish(cb) {
const subscribers = [];
const results = [];
cb(function(updatedObj) {
results.push(updatedObj);
subscribers.forEach(sub => sub(updatedObj));
});
const result = function(subscriber) {
results.forEach(res => subscriber(res));
subscribers.push(subscriber);
};
result.toPromiseFactory = toPromiseFactory.bind(null, result);
result.isThunk = true;
return result;
}
module.exports = {
thunkish,
deferrableOrImmediate(obj, fn) {
if (obj && obj.isThunk) {
return thunkish(function(sendUpdate) {
obj(function(updatedObj) {
fn(updatedObj);
sendUpdate(updatedObj);
});
});
} else {
return fn(obj);
}
},
arrayOrDeferrable(arr) {
const thunks = [];
const thunkResults = {};
const result = arr.map(function(obj, i) {
if (obj && obj.isThunk) {
thunks.push({ obj, i });
return undefined;
} else {
return obj;
}
});
if (thunks.length === 0) {
return result;
} else {
return thunkish(function(updateArray) {
thunks.forEach(({ obj: t, i }) => {
t(function(obj) {
thunkResults[i] = obj;
result[i] = obj;
if (Object.values(thunkResults).length === thunks.length) {
updateArray(result);
}
});
});
});
}
}
};