生成器函数的实例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- <script>
// 异步编程 比如 文件操作 网络操作(ajax,request) 数据库操作
// 1. 1s后控制台输出111 2s后控制台输出222 3s后控制台输出333

// 方法一: 回调地狱
setTimeout(()=>{
console.log(111);
setTimeout(()=>{
console.log(222);
setTimeout(()=>{
console.log(333);
},3000);
},2000);
},1000);
</script> -->

<script>
// 异步编程 比如 文件操作 网络操作(ajax,request) 数据库操作
// 1. 1s后控制台输出111 2s后控制台输出222 3s后控制台输出333

// 方法二:
function fn1(){
setTimeout(()=>{
console.log(111);
fn2();
},1000);
}

function fn2(){
setTimeout(()=>{
console.log(222);
fn3();
},2000);
}

function fn3(){
setTimeout(()=>{
console.log(333);
},3000);
}

function*gen(){
yield fn1();
yield fn2();
yield fn3();
}
let result = gen();
result.next();
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/weixin2623670713/p/13510325.html