说明
ES6 从入门到精通系列(全23讲)学习笔记。
解决回调地狱
比如有个需求,需要通过接口 https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city= 先获取北京的天气,然后获取上海的,最后获取广州的。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> </head> <body> <script> $.ajax({ url: "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=北京", method: "get", success(res) { console.log("res", res); $.ajax({ url: "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=上海", method: "get", success(res1) { console.log("res1", res1); $.ajax({ url: "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=广州", method: "get", success(res2) { console.log("res2", res2); // ... } }) } }) } }) </script> </body> </html>
上面就是回调地狱的展示,下面使用 Generator 处理,Generator 能让异步代码同步化
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script> </head> <body> <script> function* main() { let res = yield getData("北京"); console.log("res", res); let res1 = yield getData("上海"); console.log("res1", res1); let res2 = yield getData("广州"); console.log("res2", res2); } const ite = main(); ite.next(); function getData(city) { $.ajax({ url: `https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=${city}`, method: "get", success(res) { ite.next(res); } }) } </script> </body> </html>
其他例子:加载效果的异步
function loadUI() { console.log("加载----loading") } function getData() { setTimeout(() => { console.log("获取数据----data") }, 1000) } function hideUI() { console.log("隐藏----loading") } loadUI(); getData(); hideUI();
下面使用 Generator 处理
function* loadMain() { loadUI(); yield getData(); hideUI(); } function loadUI() { console.log("加载----loading") } function getData() { setTimeout(() => { console.log("获取数据----data") ite.next(); }, 1000) } function hideUI() { console.log("隐藏----loading") } const ite = loadMain(); ite.next();