1.es2017标准中引入了async,使得异步(async)操作更加方便
如有以下代码,定时器是异步执行的,代码并没有在阻塞等待定时器执行完再往下执行,是先打印了hello再打印的定时器:
<script>function print(){setTimeout(function(){console.log("定时器");},1000);console.log("hello");}print();</script>
如果我们想实现按顺序执行的话可以用Promise、async和awit来实现同步(sync)处理,如下:
<script>function timeout(ms) {return new Promise(function (resolve, reject) {setTimeout(function () {console.log('定时器');resolve();}, ms);});}async function asyncPrint(ms) {await timeout(ms);console.log('hello');}asyncPrint(100);</script>
2.接口同步(sync)顺序执行
我们经常会遇到接口请求是要按顺序执行的情况,比如接口2的参数需要从接口1中拿到之后传进去的,像这种情况可以用Promise、async和awit来实现同步(sync)处理,如下:
项目用到了jquery,可以到官网下载:https://jquery.com/download/
<head><meta charset="UTF-8"><title>Document</title><script src="./jquery-3.6.0.min.js"></script></head><body><script>function ajax(url) {return new Promise(function (resolve, reject) {$.getJSON(url, function (result) {resolve(result)}, function (error) {reject(error)})});}async function getInfo() {// var id_data;// // 可以用.then方法来处理得到data// await ajax("http://iwenwiki.com/api/generator/list.php").then(// (data) => {// console.log(data);// id_data = data;// },// (error) =>{// console.log(error);// }// )// console.log(id_data);// 也可以直接接收Promise对象里最终执行的函数返回值。var id = await ajax("http://iwenwiki.com/api/generator/list.php")console.log(id);var info = await ajax("http://iwenwiki.com/api/generator/id.php?id=" + id[0])console.log(info);var result = await ajax("http://iwenwiki.com/api/generator/name.php?name=" + info.name)console.log(result);}getInfo();</script></body>

