1-几种状态
// promise三种状态 pending fulfilled rejected
//penging 待定 PromisrState
var p = new Promise((resolve,reject)=>{
})
console.log(p);
// fulfilled 已完成
var f = new Promise((resolve,reject)=>{
resolve(10)
})
console.log(f);
2-状态变化
//状态变化不可逆
// pending -- fulfilled
// pending -- rejected
var p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(10)
},2000)
})
console.log(p);//pending -- fulfilled
var r = new Promise((resolve,reject)=>{
setTimeout(()=>{
reject(20)
},2000)
})
console.log(r);//pending -- rejected
3-状态触发
<!--
then 触发resolve catch触发 reject
then --触发之后的结果是promise,还是fulfilled
catch --触发之后的结果是promise, 还是fulfilled
-->
<script>
var p = Promise.resolve(10);
console.log(p);
var result = p.then(res=>{
console.log(res);
})
console.log(result);
var r = Promise.reject(20);
console.log(r);
var re = r.catch(res=>{
console.log(res);
})
console.log(re);
4-then-catch的返回值状态的变化
1—then
1-- pending --fulfilled
<!-- pending --fulfilled -->
<script>
var p = Promise.resolve(100).then(res=>{
console.log(res);
})
console.log(p); //Promise fulfilled
</script>
2-- pending --rejected then函数中报错
<script>
var p = Promise.resolve(100).then(res=>{
console.log(res);
throw "error"
})
console.log(p);//Promise rejected
</script>
2—catch
5- then函数返回报错的处理
1、
<script>
var p = Promise.resolve(10).then(res=>{
console.log(res);
throw "error"
})
var re = p.then(()=>{
console.log(20);
}).catch(res=>{
console.log(res);
})
console.log(re);
</script>
2、
<script>
var r = Promise.reject(20).catch(res=>{
console.log(res); //20
})
console.log(r); //Promise fulfilled
r.catch(()=>{ //catch不能触发
console.log("error"); //不输出
}).then(()=>{ //then触发
console.log(200); //200
})
</script>
6- catch函数返回报错的处理
<script>
var r = Promise.reject(10).catch(res=>{
console.log(res); //10
throw "error"
})
console.log(r);
r.then(()=>{
console.log(200);
}).catch(()=>{
console.log("error");
})
</script>