4

promise如何串连多个操作任务

promise的then()返回一个新的promise, 通过then的链式调用串连多个同步/异步任务
new Promise((resolve, reject) => {  
  setTimeout(() => {  
    console.log("执行任务1(异步)")  
    resolve(1)  
  }, 1000);  
}).then(  
  value => {  
    console.log('任务1的结果: ', value)  
    console.log('执行任务2(同步)')  
    return 2  
  }  
).then(  
  value => {  
    console.log('任务2的结果:', value)  
  
    return new Promise((resolve, reject) => {  
      // 启动任务3(异步)  
  setTimeout(() => {  
        console.log('执行任务3(异步))')  
        resolve(3)  
      }, 1000);  
    })  
  }  
).then(  
  value => {  
    console.log('任务3的结果: ', value)  
  }  
)
执行结果:
1秒后
执行任务1(异步)
任务1的结果:  1
执行任务2(同步)
任务2的结果: 2
再过1秒后
执行任务3(异步))
任务3的结果:  3

promise异常传透/穿透

1. 当使用promise的then链式调用时, 可以在最后指定失败的回调,  
2. 前面任何操作出了异常, 都会传到最后失败的回调中处理
new Promise((resolve, reject) => {  
  // resolve(1)  
  reject(1)  
}).then(  
  value => {  
    console.log('onResolved1()', value)  
    return 2  
  },  
  // reason => {throw reason}  //如果没有reject回调,就类似这样往下传递
).then(  
  value => {  
    console.log('onResolved2()', value)  
    return 3  
  },  
  // reason => {throw reason}  //如果没有reject回调,就类似这样往下传递
).then(  
  value => {  
    console.log('onResolved3()', value)  
  },  
  // reason => Promise.reject(reason)  //如果没有reject回调,就类似这样往下传递
).catch(reason => {  
  console.log('onReejected1()', reason)  
  // throw reason  
 // return Promise.reject(reason)
 }).then(  
  value => {  
    console.log('onResolved3()', value)  
  },  
  reason => {  
    console.log('onReejected2()', reason)  
  }  
)
执行结果:
onReejected1() 1
onResolved3() undefined

中断Promise链

中断promise链?  
1. 当使用promise的then链式调用时, 在中间中断, 不再调用后面的回调函数  
2. 办法: 在回调函数中返回一个pending状态的promise对象
new Promise((resolve, reject) => {  
  resolve(1)  
}).then(  
  value => {  
    console.log('onResolved1()', value)  
    return new Promise(() => {}) // 返回一个pending的promise  中断promise链  
  },  
).then(  //不会进入这个回调
  value => {  
    console.log('onResolved2()', value)  
  },  
  reason => {  
    console.log('onResolved2()', reason)  
  },  
)
执行结果:
onResolved1() 1
代码已同步更新到github上

https://github.com/hnt815/promise

Promise系列文章

Promise从两眼发懵到双眼放光(1)-准备篇
Promise从两眼发懵到双眼放光(2)-Promise基础
Promise从两眼发懵到双眼放光(3)-Promise的几个关键问题(一)
Promise从两眼发懵到双眼放光(4)-Promise的几个关键问题(二)
Promise从两眼发懵到双眼放光(5)-手写Promise之整体结构
Promise从两眼发懵到双眼放光(6)-手写Promise之构造函数
Promise从两眼发懵到双眼放光(7)-手写Promise之then方法和catch方法
Promise从两眼发懵到双眼放光(8)-手写Promise之resolve,reject,all,race方法
Promise从两眼发懵到双眼放光(9)-async和await


ntyang
165 声望29 粉丝

非典型性代码搬运工,搞点儿事情