1 function* generatorExample(){
2 let result = yield 'hello'; // 状态值为hello
3 yield 'generator'; // 状态值为generator
4 }
1 var num = 1;
2
3 function AsyncUtil() {
4 setTimeout(() => {
5 console.log("异步任务" + num + "执行");
6
7 let data = "异步任务" + num + "的返回数据xxxx";
8
9 num++;
10 GU.next(data); //继续执行yield之后的语句
11 }, 2000);
12 }
13
14 function* generatorUtil() {
15 console.log("函数开始执行");
16
17 let result = yield AsyncUtil(); //遇到yield就暂停,执行异步任务,让异步任务调用generatorUtil继续执行。
18 console.log("异步任务执行成功,返回值:" + result);
19 console.log("函数继续执行");
20
21 result = yield AsyncUtil();
22 console.log("异步任务执行成功,返回值:" + result);
23
24 console.log("函数执行结束");
25
26 }
27
28 let GU = generatorUtil();
29 console.log(GU);
30
31 GU.next(); //只有个使用next方法才能调用执行