知识结构:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ad9264d10a93ef84c4a06978d5194d1f.png#pic_center)
Promise的使用:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Loading...</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div>
1.使用Promise进行网络的访问</br>
promise是什么:promise是一种异步编程的解决方案,从语法上讲,promise是一个对象,可以异步的获取消息。</br>
a.实例化 Promise对象,构造函数中传递函数,该函数中用于处理异步任务</br>
b.resolve和reject两个参数用于处理成功和失败两种情况,并通过p.then获取处理结果</br>
<script type="text/javascript">
var p = new Promise(function (resolve, reject) {
var flag = false;
if (flag == true) {
resolve("helloworld");
} else {
reject("sonmethingerror");
}
});
p.then(function (data) {
console.log("作用域1的数据", data);
}, function (info) {
console.log("作用域1的数据", info)
})
</script>
</div>
</br>
</br>
<div>
2.基于promise的ajax的使用
<script type="text/javascript">
function req(url) {
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
if (request.readyState == 4 && request.status == 200) {
return resolve(request.responseText);
} else {
return reject({
"code": 500,
"msg": "error"
});
}
}
request.open("get", url);
request.send(null);
});
}
var p2 = new req("http://127.0.0.1/pro1");
p2.then((data) => {
console.log(data);
}, (info) => {
console.log(info);
})
var url = "http://127.0.0.1/time";
req(url).then((data) => {
console.log(data);
})
req(url).then((data) => {
console.log(data);
})
req(url).then((data) => {
console.log(data);
})
</script>
</div>
</br>
</br>
<div>
3.promise的常用的api 一</br>
p.then()得到异步任务的正确结果</br>
p.catch()获取异常信息</br>
p.finally()成功与否都会执行(尚且不是正式标准)</br>
(resolve, reject)二者只能存其一,两者同时存在resolve生效
<script type="text/javascript">
var p3 = () => {
return new Promise(((resolve, reject) => {
reject</