-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.js
73 lines (69 loc) · 1.43 KB
/
generator.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
function* mtGenerator() {
console.log( yield Promise.resolve(1) )
console.log(yield Promise.resolve(2))
console.log(yield Promise.resolve(3))
}
const gen = mtGenerator()
// gen.next().value.then(res => {
// console.log(res)
// })
// gen.next().value.then(res => {
// console.log(res)
// })
// gen.next().value.then(res => {
// console.log(res)
// })
// gen.next().value.then(val => {
// gen.next(val).value.then(val => {
// gen.next(val).value.then(val => {
// gen.next(val)
// })
// })
// })
// =============================
/*
function run(gen) {
var g = gen()
function _next(val) {
var res = g.next(val)
if(res.done) return res.value
res.value.then(val => {
_next(val)
})
}
_next()
}
*/
run(mtGenerator)
function run(gen) {
return new Promise((resolve, reject) => {
var g = gen()
function _next(val) {
try {
var res = g.next(val)
} catch (error) {
return reject(error)
}
if(res.done) {
return resolve(res.value)
}
Promise.resolve(res.value).then(val => {
_next(val)
}, err => {
g.throw(err)
})
}
_next()
})
}
function* myGenerator() {
try {
console.log(yield Promise.resolve(1))
console.log(yield 2) //2
console.log(yield Promise.reject('error'))
} catch (error) {
console.log(error)
}
}
const result = run(myGenerator) //result是一个Promise
//输出 1 2 error