首页 > 其他 > 详细

09 promise then

时间:2020-06-26 19:18:27      阅读:82      评论:0      收藏:0      [点我收藏+]

then() 方法返回一个 Promise
链式调用:then里面回调函数(成功回调和失败回调),凡事这两个回调函数里面抛出错误或者返回一个已经是拒绝状态的 Promise
那么 then 返回的 Promise 对象将是rejected状态,走下一个then里面的失败回调函数
 
catch() 方法返回一个Promise,并且处理拒绝的情况。它的行为与调用Promise.prototype.then(undefined, onRejected) 相同
 

try-catch

有catch穿透的效果

new Promise((resolve, reject) => {
  resolve(1)
}).then(data => {
  console.log(data)
  return 2
 
}).then(data => {
  console.log(data);
  return Promise.reject(20) 

//一旦promise变为rejected直接走catch,不是一次性到最后的catch ,每一个then里面没有写失败回调函数,但是默认写了reason=>{throw reason}
//或者 resaon=>Promise.reject(reason)
}).then(data => { console.log(data) }).catch(err => { console.log(err) }) //1 2 20

then两个回调函数

 then两个回调函数,上一个then的promise状态变为rejected 状态,就走临近下一个then的失败回调函数,不会直接调到最后一个

//
new Promise((resolve, reject) => {
  resolve(1)
})
  .then(data => {
    console.log(data)
    return Promise.reject(20)

  }, err => {
    console.log(err)
    return 3
  })

  .then(data => {
    console.log(data);

  }, err => {
    console.log(err);
    return 3

  })

  .then(data => {
    console.log(data);

  }, err => {
    console.log(err);

  })
  //1 20 3

 then链式调用里面含有异步操作

 

new Promise((resolve, reject) => {
  resolve(1)
}).then(data => {
  console.log(data)
  return 2
}).then(data => {
  console.log(data)
  // then链式调用,如果里面有异步,需要返回新的promise对象,不然下一个then拿不到这个异步操作的结果
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(3)
    }, 1000);

  })
  /* 异步操作直接写,下一个then的data就是默认值undefined。拿不到异步操作的结果
  setTimeout(() => {
    return 10
  }, 1000);
   */
}).then(data => {
  console.log(data)
})

中断promise链

return new Promise(()=>{})

 

09 promise then

原文:https://www.cnblogs.com/xiaoliziaaa/p/13195637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!