异步编程(Asynchronous) - 7 Promise - catch

使用catch注册失败回调

  • catch方法就是 then方法的一个别名,第一个参数传入undefined
ajax('/api/users11.json')
  .then(function (users) {
    info('onFullfilled', users)
  }).catch(function (error) { // catch方法就是then方法的一个别名
    info('onRejected', error)
  })
ajax('/api/users11.json')
  .then(function (users) {
    info('onFullfilled', users)
  }).then(undefined, function (error) { // catch方法就是then方法的一个别名,第一个参数传入undefined
    info('onRejected', error)
  })
// ------------------- 使用catch注册失败回调
ajax('/api/users11.json')
  .then(function onFullfilled(users) {
    info('onFullfilled', users)
    return ajax('/error-url') // 返回一个Promise
  }) // 每一个then方法会返回一个全新的Promise对象 {}
  .catch(function onRejected(error) { // catch方法就是then方法的一个别名
    // 这个失败的回调是注册在上一个(then方法)返回的Promise对象上,这个对象是失败的
    info('onRejected', error) // onRejected Error: Not Found
  })

链式回调 =>>>> 建议使用catch捕获,这种方式更像是给整个链条注册的回调

posted @ 2020-08-19 17:10  荣光无限  阅读(71)  评论(0)    收藏  举报