(1)Promise的介绍
(1) 异步编程
(2)为什么要用Promise?
(1)指定回调函数的方式更加灵活
(2)支持链式调用,可以解决回调地狱问题
回调地狱-------->(十分复杂)
(2)Promise的初体验
实现以下效果
(1)普通写法
<!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>
<div class="container">
<h2 class="page-header">Promise初体验</h2>
<button class="btn btn-primary" id="btn">点击抽奖</button>
</div>
<script>
//生成随机数
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
}
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
setTimeout(() => {
let n = rand(1, 100);
if (n <= 30) alert("恭喜恭喜,奖品为10万 RMB 劳斯莱斯优惠券");
else alert("再接再厉");
}, 2000);
});
</script>
</body>
</html>
(2)Promise写法
<script>
//生成随机数
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
}
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
let n = rand(1, 100);
if (n <= 30) resolve();
else reject();
}, 2000);
});
p.then(
() => {
alert("恭喜恭喜,奖品为10万 RMB 劳斯莱斯优惠券");
},
() => {
alert("再接再厉");
}
);
});
</script>
(1)Promise写法(改进)传了数字结果---->n
<script>
//生成随机数
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
}
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
let n = rand(1, 100);
if (n <= 30) resolve(n);
else reject(n);
}, 2000);
});
p.then(
(n) => {
alert("恭喜恭喜,奖品为10万 RMB 劳斯莱斯优惠券,中奖数字为" + n);
},
(n) => {
alert("再接再厉,数字为" + n);
}
);
});
</script> <script>
//生成随机数
function rand(m, n) {
return Math.ceil(Math.random() * (n - m + 1)) + m - 1;
}
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
let n = rand(1, 100);
if (n <= 30) resolve(n);
else reject(n);
}, 2000);
});
p.then(
(n) => {
alert("恭喜恭喜,奖品为10万 RMB 劳斯莱斯优惠券,中奖数字为" + n);
},
(n) => {
alert("再接再厉,数字为" + n);
}
);
});
</script>
(3)Promise实践练习
(1)fs读取文件(普通写法)
(2)Promise写法