Promise 对象
认识Promise对象
语法
new Promise((resolve, reject)=>{
resolve();// reject();
}).then(()=>{
console.log("resolve!");
}).catch(()=>{
console.log("reject!");
})
Promise 对象执行了 resolve 就不执行reject
也就是说,执行了 .then 就不执行 .catch
resolve/reject 类型是 Function
案例1:打印 1-3 每隔500ms
function GetTime() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 500)
});
}
var num = 1;
GetTime().then(() => {
console.log(num++);
return GetTime();
}).then(() => {
console.log(num++);
return GetTime();
}).then(() => {
console.log(num++);
return GetTime();
});
案例2 做一个简易的红绿灯 每个2秒切换灯
<!-- HTML 结构 -->
<!doctype html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>简易红绿灯</title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<!--引入一下js-->
</body>
</html>
/*css 样式*/
*{
margin: 0;
padding: 0;
}
div{
width: 50px;
height: 50px;
border: 1px solid #000000;
box-shadow: 0px 0px 4px #cccccc inset;
border-radius: 50%;
margin-left: 20px;
}
// js
var divs = document.querySelectorAll("div");
function GetTime(){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve();
},2000)
});
}
GetTime().then(()=>{
divs[0].style.backgroundColor = "red";
return GetTime();
}).then(()=>{
divs[1].style.backgroundColor = "green";
divs[0].style.backgroundColor = "rgba(0,0,0,0)";
return GetTime();
}).then(()=>{
divs[2].style.backgroundColor = "yellow";
divs[1].style.backgroundColor = "rgba(0,0,0,0)";
return GetTime();
});
Promise 三种状态
pending 刚进入promise状态
fulfilled 执行了resolve 后
rejected 执行了reject 后
Promise.all()
将所有的Promise对象中resolve 的参数内容合成数组
用于遍历所有的promise对象
Promise.race()
谁快谁先完成
Promise.resolve().then(()+>{});
new promise((resolve, reject)=>{
resolve();
}).then(()=>{});
Promise.reject().catch(()=>{});
new promise((resolve, reject)=>{
reject();
}).catch(()=>{});
隐士返回一个promise对象
// 这是一个promise对象
loadImage("./img/5-.jpg")
.then((img)=>{
console.log("aaa", img);
// 相当于
returnPromise.resolve();
}).then((img)=>{
console.log("bbb", img); // 返回的resolve 无参数,所以打印出bbb undefined
})
async await
语法 :
async function fn(){
return "a";
}
var p = fn();
log(a) => 得到的一个结果是 Promise
await 只能等待 promise 执行 resolve 或者 reject 后的内容,并且 await 只能出现在 async 函数中