shly / Blog-New

学习笔记
0 stars 0 forks source link

关于Promise的笔记 #9

Open shly opened 6 years ago

shly commented 6 years ago

一个Promise执行之后结果为reject,如果reject被处理了,则会继续执行之后的then方法,如果没有被处理,则reject将向下传播,直到它被处理。如果到最后也没有被处理将会报错。示例

let test = new Promise (function (resolve, reject) {
  let flag = false
  if (flag) {
    resolve(1)
  } else {
    reject(2)
  }
})
test.then(function (res) {
  console.log(res)
}).then(function () {
  console.log('after test')
})

输出 (node:11272) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): 2 (node:11272) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

let test = new Promise (function (resolve, reject) {
  let flag = false
  if (flag) {
    resolve(1)
  } else {
    reject(2)
  }
})
test.then(function (res) {
  console.log(res)
}).then(function () {
    console.log('after test')
}).catch(function (error) {
    console.log(error)
})

输出 2

let test = new Promise (function (resolve, reject) {
  let flag = false
  if (flag) {
    resolve(1)
  } else {
    reject(2)
  }
})
test.then(function (res) {
  console.log(res)
}).catch(function (error) {
    console.log(error)
}).then(function () {
    console.log('after test')
})

输出 2 after test

shly commented 6 years ago

使用.then的第二个参数捕获异常和使用.catch的区别?

.then 的第二个处理错误的函数捕获不了第一个处理成功的函数抛出的错误,而后续的 .catch 可以捕获之前的错误。