一、异步编程的方法
1、回调函数
2、事件监听
3、发布/订阅
4、Promise对象
5、Generator函数
6、async函数
二、例子
1、回调函数
setTimeout(()=>{
console.log(111);
setTimeout(()=>{
console.log(222);
setTimeout(()=>{
console.log(333);
},3000)
},2000)
},1000)
2、Generator函数
function one() {
setTimeout(() => {
console.log(111);
i.next();
}, 1000);
};
function two() {
setTimeout(() => {
console.log(222);
i.next();
}, 2000);
};
function three() {
setTimeout(() => {
console.log(333);
}, 3000);
};
function* gen() {
yield one();
yield two();
yield three();
}
let i = gen();
i.next()
3、asyn函数
function one() {
setTimeout(() => {
console.log(111);
}, 1000);
};
function two() {
setTimeout(() => {
console.log(222);
}, 3000);
};
function three() {
setTimeout(() => {
console.log(333);
}, 6000);
};
async function gen() {
await one();
await two();
await three();
}
gen()
4、Promise对象
<!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>
</head>
<body>
<script>
// 基于promise封装ajax
let axios = {
get(url) {
return new Promise(function (resolve, reject) {
// ajax网络请求
// 1.创建XHR实例
let xhr = new XMLHttpRequest();
// 2.设置请求行
xhr.open('get', url,);
// 3.设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.responseType = 'json';
// 4.发送请求
xhr.send();//接受一个参数,这个参数会放到请求体中
// 5.监听
xhr.onreadystatechange = function () {
console.log(this);
if (this.readyState == 4) {
if(this.status == 200){
resolve(this.response)
}else {
reject(this.response)
}
}
}
})
}
}
let baseUrl = 'http://47.100.226.238:8888'
axios.get(baseUrl+'/index/category/findAll').then((res)=>{
console.log(res);
}).catch((res)=>{
console.log(res);
})
</script>
</body>
</html>