Promise.then的操作手法

127 阅读1分钟
promise.then()返回的新promise的结果状态由什么决定呢?
由then()指定的回调函数 执行结果 来决定!!
(1)如果抛出异常了,将会返回rejected 的promise reason为抛出的异常
(2)如果返回的是非promise的任意值 ,新promise变为resolved value为返回的值
(3)如果返回的是另一个新的promise ,此promise的结果回成为新的promise 的结果

代码如下:
new Promise((resolve,reject)=>{
  setTimeout(() => {
    resolve(1)
  }, 1000);  
}).then(
    //.then 后面执行 哪个函数需要根据上面的pormise结果来决定  上面调用的resolve就是 执行第一个
    //否则执行第二个
  value =>{
    console.log('任务1的结果:',value);
    console.log('执行任务2的同步');
    return 2  // 这个return决定后面的.then 是后面传入的value值  将返回一个成功的promise 值为2
    //也可以 throw new Error('错误了') 将返回一个失败的promise reason为错误了
  },
  reason =>{
      console.log('任务1失败',reason)
  }
).then(
  value =>{ 
    console.log('任务2的结果',value);
      //如果返回的是一个新的promise 则此次then的返回结果会成为新的promise
   return new Promise((resolve,reject)=>{
      setTimeout(() => { 
      console.log('执行任务3(异步)');
      resolve(3)
    }, 5000);
    })
  // 不能直接这么写的啊 在定时器里面return 3 外面是接受不到的
  //  setTimeout(() => { 
  //    console.log('执行任务3(异步)');
  //    return 3
  //   }, 5000);
},
).then(
  value =>{
    console.log('任务3的结果:',value);
  }
)