-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncSimulate.js
More file actions
41 lines (34 loc) · 810 Bytes
/
asyncSimulate.js
File metadata and controls
41 lines (34 loc) · 810 Bytes
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
/**
* @Description: 简单模拟async/await,其本质上是 Generator + 自动执行器的语法糖
* @Author: oceanhhan
* @Date: 2026-03-11 19:14:35
*/
export default function asyncSimulate(generatorFunc) {
return new Promise((resolve, reject) => {
const generator = generatorFunc();
function run(result) {
if (result.done) {
resolve(result.value);
return;
}
const value = Promise.resolve(result.value);
value.then(
(res) => {
run(generator.next(res));
},
(err) => {
try {
run(generator.throw(err));
} catch (e) {
reject(e);
}
});
}
try {
run(generator.next());
} catch (e) {
reject(e);
}
});
}
// examples: ./examples/*