js之Promise练习


红绿黄每隔一秒亮一次;如何让三个灯不断交替重复亮灯?
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
function red(){
console.log('red- ', new Date());
}
function green(){
console.log('green- ', new Date());
}
function yellow(){
console.log('yellow- ', new Date());
}

// 地域回调
function fn() {
setTimeout(() => {
red()
setTimeout(() => {
green()
setTimeout(() => {
yellow()
fn()
}, 1000)
}, 1000)
}, 1000)
}
fn()

// Promise实现
function tic(callback, timer) {
return new Promise((resolve, reject) => {
setTimeout(() => {
callback()
resolve()
}, timer)
})
}
function fn1 () {
return tic(red, 1000).then(() => {
return tic(green, 1000)
}).then(() => {
return tic(yellow, 1000)
}).then(() => {
fn1()
})
}
fn1()

// Generator实现
function* light(){
yield tic(1000, red);
yield tic(2000, green);
yield tic(3000, yellow);
}
function loop(iterator, gen){
var result = iterator.next();
if (result.done) {
loop(gen(), gen)
} else {
result.value.then(function(){
loop(iterator, gen)
})
}
};
loop(light(), light);

// async, await实现
(async function (){
while(true){
await tic(3000, red);
await tic(2000, green);
await tic(1000, yellow);
}
})();