-
Notifications
You must be signed in to change notification settings - Fork 0
/
go.js
49 lines (45 loc) · 1.19 KB
/
go.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
/** -----------------------------------------------------------------------------------------------
* go.js
* An asynchronous driver for generator.
* author: leadzen(李战)
*/
var go = function (toString, reIsGenerator) {
function go(any) {
return isGenerator(any)
? Promise.resolve().then(next)
: Promise.resolve(any);
function next(value) {
return Promise.resolve(any.next(value))
.then(function (state) {
value = go(state.value);
return state.done ? value : value.then(next);
});
}
}
return Object.defineProperties(go, {
all: {
value(iterable) {
return Promise.all(function* (iterable) {
for (var value of iterable) {
yield go(value);
}
}(iterable));
}
},
race: {
value(iterable){
return Promise.race(function* (iterable) {
for (var value of iterable) {
yield go(value);
}
}(iterable));
}
}
});
function isGenerator(any) {
return reIsGenerator.test(toString.call(any));
}
}(
Object.prototype.toString, // toString
/\[object (?:Async)?Generator\]/ // reIsGenerator
);