Promise.reject和try...catch..捕获

293 阅读1分钟

1、什么是 Uncaught(in promise) error?

在上面示例中,创建了一个Promise并使用reject方法将其状态设置为rejected。但是,没有在后续代码中处理这个错误,此时就会导致 Uncaught(in promise) error。

  async function test_promise() {
    await Promise.reject({ type: "error" }) //不加then会报错  console不打印
    console.log("gggg");
  }
​

15CBC2DD-3E32-4cbd-9F63-3D704326B028.png

如何处理???

  function resolved(result) {
    console.log('Resolved');
  }
​
  function rejected(result) {
    console.log(result, "rejected");
  }  
// 加上then不报错 走rejected,console打印
async function test_promise() {
    await Promise.reject("error").then(resolved,rejected)
    console.log("gggg");
  }

2、直接Promise.reject会被try..catch捕获到么?

答案:不会

  async function asyncFunction() {
    try {
      new Promise((resolve, reject) => {
        reject('error');
      })
      //Promise.reject()上面写法和这样写一个效果
    } catch (error) {
      console.log("~~~~", error); // 不打印
    }
  }
  asyncFunction() // Uncaught(in promise) error

上面执行代码会报错Uncaught(in promise) errorcatch不能捕获到???为什么呢?

因为这个 Promise 会立即被拒绝(rejected),但由于 Promise 的本质是异步的,reject 调用本身不会立即抛出错误给当前的同步执行栈。因此,外部的 try...catch 无法捕获到这个错误,因为 try...catch 只在当前执行栈的同步代码块中有效。

  async function asyncFunction() {
    try {
      await Promise.reject("reject error")
    } catch (error) {
      console.log("~~~~", error); // 输出:reject error
    }
  }
  asyncFunction() 

当你使用 await 关键字等待一个 Promise 时,await 会暂停 async 函数的执行,直到 Promise 解决(fulfilled)或拒绝(rejected)。如果 Promise 被拒绝,await 表达式会抛出一个错误,这个错误可以被 async 函数外部的 try...catch 捕获。和**try...catch 只在当前执行栈的同步代码块中有效的逻辑一致**,等待执行并报错

3、看下边的代码

  async function test_try() {
    try {
      const res = await new Promise((resolve, reject) => {
        console.log("声明promise实例");
      })
      console.log("执行了么???");//不执行
      Promise.reject() // 不执行 因为上面得promise没有resolve也没有reject,所以被永远等待,被挂起了
    } catch (e) {
      console.log("?????catch");//不执行
      return Promise.resolve({ type: "catch_error", value: e })
    }
  }