-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.html
121 lines (104 loc) · 2.97 KB
/
generator.html
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
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<title>await/async generator原理</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script>
function* Generator() {
const a = yield 1;
console.log(a)
yield 2;
return 'end';
}
const gen = Generator();
console.log(gen.next());
console.log(gen.next('a'));
console.log(gen.next());
console.log(gen.next());
// for(const i of gen) {
// console.log(i)
// }
class Context {
prev = 0;
next = 0;
done = false;
}
function getValue(context, value) {
let a;
while (true) {
context.prev = context.next;
switch (context.next) {
case 0:
context.next = 2;
context.done = false;
return 1;
case 2:
a = value;
console.log(a);
context.next = 4;
context.done = false;
return 2;
case 4:
context.done = true;
context.next = 'end';
return 'end';
case 'end':
context.done = true;
return;
}
}
}
function Gen() {
const context = new Context();
return {
next: function (value) {
return {
value: getValue(context, value),
done: context.done
}
}
}
}
const gen1 = Gen();
console.log(gen1.next());
console.log(gen1.next('a'));
console.log(gen1.next());
console.log(gen1.next());
function asyncFunc() {
awaitfunc(1);
awaitfunc(2);
awaitfunc('end');
}
function next(value, done) {
return {
value,
done
}
};
function awaitfunc(value) {
next(value);
}
function foo() {
const gen2 = Generator();
return new Promise((resolve, reject) => {
function next() {
const obj = gen2.next();
console.log(obj);
const { value, done } = obj;
if (!done) {
Promise.resolve(value).then(val => next(val))
}
return value;
}
const value = next();
resolve(Promise.resolve(value));
})
}
foo().then(res => {
console.log(res)
});
</script>
</body>
</html>