-
Notifications
You must be signed in to change notification settings - Fork 38
/
lazyman-promise.js
67 lines (55 loc) · 1.29 KB
/
lazyman-promise.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
export function LazyManAsync(name) {
return new LazyManFactory(name);
}
function LazyManFactory(name) {
this.tasks = [];
this.tasks.push(() => {
return new Promise((resolve, reject) => {
console.log("hi", name);
resolve();
})
});
setTimeout(() => {
this.run();
}, 0);
}
LazyManFactory.prototype.run = function () {
if (this.tasks.length === 0) {
return;
}
let task = this.tasks.shift();
task().then(() => {
this.run();
}).catch(() => {
this.run();
})
}
LazyManFactory.prototype.sleep = function (time) {
this.tasks.push(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time * 1000)
})
})
return this;
}
LazyManFactory.prototype.eat = function (name) {
this.tasks.push(() => {
return new Promise((resolve, reject) => {
console.log("eat:", name);
resolve();
})
})
return this;
}
LazyManFactory.prototype.sleepFirst = function (time) {
this.tasks.unshift(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time * 1000)
})
})
return this;
}