javascript - Promise 中的异步函数会抛出错误并且不会拒绝

标签 javascript asynchronous error-handling promise catch-block

如果有一个包含异步函数的 promise ,并且如果异步函数中发生错误,则 promise 不会捕获,而是会抛出错误并使应用程序崩溃,这是我不明白的。

显然我想处理这个错误,你知道为什么 Promise 会这样吗?有什么办法可以解决它?

谢谢

// this promise will have an error since param is not defined,
// and the promise won't be caught
function randomPromise(param) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            param[0] = 11;
        }, 2000);
    });
}

randomPromise()
.then(() => {
    console.log('nothing');
})
.catch((e) => {
    console.log('with set timeout or any async function in the promise, the error caused by \'param[0] = 11;\' wont bring the control here into the catch block just throws an error and crashes the application');
    console.log(e);
});

// this promise will have an error since param is not defined
// but the promise will be caught
function randomPromiseGoesToCatchBlock(param) {
    return new Promise((resolve, reject) => {
        param[0] = 11;
    });
}

randomPromiseGoesToCatchBlock()
.then(() => {
    console.log('nothing');
})
.catch((e) => {
    console.log('without the setTimeout function or any async function the error caused by \'param[0] = 11;\' brings the control here into the catch block');
    console.log(e);
});

最佳答案

Promise 构造函数中抛出的错误以及异步发生的错误需要显式 try/catch ed,以便调用reject,从而将Promise控制流转移到Promise的catch中。例如:

// this promise will have an error since param is not defined, and the promise wont be catched
function randomPromise(param) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        param[0] = 11;
      } catch(e) {
        reject(e);
      }
    }, 2000);
  });
}

randomPromise()
  .catch((e) => {
    console.log(e.message);
  });

否则,resolvereject 都不会被调用,并且错误是异步的,因此创建 Promise 的线程已经结束,因此解释器不会'我不知道抛出的错误应该拒绝该 Promise,而无需您明确告诉它。

相反,在 Promise 构造函数内同步抛出的错误将自动导致构造的 Promise 立即拒绝。

关于javascript - Promise 中的异步函数会抛出错误并且不会拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54611416/

相关文章:

javascript - 按顺序解决 Promise,如果序列中的 Promise 之一抛出错误,则中断序列

ajax - 从 AJAX 获取错误消息时出现问题 - 仅在电话上出错

javascript - NodeJS 表达未解析的函数或方法 get()

Javascript onclick 改变 id img

提交时的 JavaScript

java - 如何记录错误级别为ERROR的消息

java - 调试数组和 for-loop + if 语句

javascript - 将 float 作为自然数排序

ios - 从解析中下载多个 (4<) PFFile 并使它们同步到正确的数组中

javascript - 同步两个 HTTP 请求