1.16 Generator的应用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>1.16 Generator的应用</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<script>
// ajax是典型的异步操作.通过Generator函数部署Ajax操作,可以用同步的方式表达
function* main() {
const res = yield request(
'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
);
console.log(res);
console.log('1111');
}
let it = main();
it.next()
// https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976
function request(url) {
// 假设
$.ajax({
url,
method: 'get',
success(res) {
// it.next(res);
it.next(res);
}
})
}
// Generator 函数用来处理异步操作
function* load() {
loadUI();
yield showData();
hideUI();
}
let itLoad = load();
// console.log(itLoad);
// 第一次调用会显示加载UI界面,并且异步的加载数据
itLoad.next();
function loadUI() {
console.log('加载loading界面.....');
}
function showData(){
setTimeout(() => {
console.log('数据加载完成.....');
// 第二调用,会调用hideUI(),隐藏Loading
itLoad.next();
}, 1000);
}
function hideUI() {
console.log('隐藏loading....');
}
// 给任意对象部署Interator接口
</script>
</body>
</html>