1-几种状态

  1. // promise三种状态 pending fulfilled rejected
  2. //penging 待定 PromisrState
  3. var p = new Promise((resolve,reject)=>{
  4. })
  5. console.log(p);
  6. // fulfilled 已完成
  7. var f = new Promise((resolve,reject)=>{
  8. resolve(10)
  9. })
  10. console.log(f);

2-状态变化

  1. //状态变化不可逆
  2. // pending -- fulfilled
  3. // pending -- rejected
  4. var p = new Promise((resolve,reject)=>{
  5. setTimeout(()=>{
  6. resolve(10)
  7. },2000)
  8. })
  9. console.log(p);//pending -- fulfilled
  10. var r = new Promise((resolve,reject)=>{
  11. setTimeout(()=>{
  12. reject(20)
  13. },2000)
  14. })
  15. console.log(r);//pending -- rejected

image.png

3-状态触发

  1. <!--
  2. then 触发resolve catch触发 reject
  3. then --触发之后的结果是promise,还是fulfilled
  4. catch --触发之后的结果是promise, 还是fulfilled
  5. -->
  6. <script>
  7. var p = Promise.resolve(10);
  8. console.log(p);
  9. var result = p.then(res=>{
  10. console.log(res);
  11. })
  12. console.log(result);
  13. var r = Promise.reject(20);
  14. console.log(r);
  15. var re = r.catch(res=>{
  16. console.log(res);
  17. })
  18. console.log(re);

image.pngimage.png

4-then-catch的返回值状态的变化

1—then


  1. 1-- pending --fulfilled
  2. <!-- pending --fulfilled -->
  3. <script>
  4. var p = Promise.resolve(100).then(res=>{
  5. console.log(res);
  6. })
  7. console.log(p); //Promise fulfilled
  8. </script>
  1. 2-- pending --rejected then函数中报错
  2. <script>
  3. var p = Promise.resolve(100).then(res=>{
  4. console.log(res);
  5. throw "error"
  6. })
  7. console.log(p);//Promise rejected
  8. </script>

2—catch

5- then函数返回报错的处理

  1. 1
  2. <script>
  3. var p = Promise.resolve(10).then(res=>{
  4. console.log(res);
  5. throw "error"
  6. })
  7. var re = p.then(()=>{
  8. console.log(20);
  9. }).catch(res=>{
  10. console.log(res);
  11. })
  12. console.log(re);
  13. </script>

image.png

  1. 2
  2. <script>
  3. var r = Promise.reject(20).catch(res=>{
  4. console.log(res); //20
  5. })
  6. console.log(r); //Promise fulfilled
  7. r.catch(()=>{ //catch不能触发
  8. console.log("error"); //不输出
  9. }).then(()=>{ //then触发
  10. console.log(200); //200
  11. })
  12. </script>

image.png

6- catch函数返回报错的处理

  1. <script>
  2. var r = Promise.reject(10).catch(res=>{
  3. console.log(res); //10
  4. throw "error"
  5. })
  6. console.log(r);
  7. r.then(()=>{
  8. console.log(200);
  9. }).catch(()=>{
  10. console.log("error");
  11. })
  12. </script>

image.png