一、promise有几种状态 PromiseState


1、 pending
  1. var p = new Promise((resolve,reject)=>{
  2. })


2、fulfilled
  1. var f = new Promise((resolve,reject)=>{
  2. resolve(10);
  3. })


3、rejected
  1. var r = new Promise((resolve,reject)=>{
  2. reject(20);
  3. })


二、状态的变化

状态的变化是不可逆的

  1. pending --> fulfilled
  2. var p = new Promise((resolve,reject)=>{
  3. setTimeout(()=>{
  4. resolve(10);
  5. })
  1. pending --> rejected
  2. var r = new Promise((resolve,reject)=>{
  3. setTimeout(()=>{
  4. reject(20)
  5. },2000)
  6. })


三、状态的触发

  1. resolve then -->触发之后的结果是Promise,状态fulfilled
  2. reject catch -->触发之后的结果是Promise,状态fulfilled
  1. var p = Promise.resolve(10);
  2. var r = Promise.reject(20);
  3. console.log(p)
  4. var result = p.then(res=>{
  5. console.log(res)
  6. })
  7. console.log(result)
  8. var result02 = r.catch(res => {
  9. console.log(res)
  10. })
  11. console.log(result02)


四、then和catch返回值的状态的变化


1-1 pending—>resolve
  1. var p = Promise.resolve(100).then(res=>{
  2. console.log(res)
  3. })
  4. console.log(p) //Promise fulfilled


1-2 then函数中报错,返回值的状态为rejected
  1. var p = Promise.resolve(100).then(res=>{
  2. console.log(res);
  3. throw "error"
  4. })
  5. console.log(p) //Promise rejected


1-3 then函数返回值报错的处理
  1. var p = Promise.resolve(10).then(res=>{
  2. console.log(res);
  3. throw "error"
  4. })
  5. /*
  6. p Promise rejected
  7. */
  8. var res = p.then(()=>{
  9. console.log("20");
  10. }).catch(res=>{
  11. console.log(res)
  12. })
  13. console.log(res)


1-4 catch之后的报错
  1. var r = Promise.reject(10).catch(res=>{
  2. console.log(res); //10
  3. throw "error";
  4. })
  5. r.then(()=>{
  6. console.log(200);
  7. }).catch(err=>{
  8. console.log(err);
  9. })