承诺中的异步函数抛出错误并且不拒绝

asynchronous function in promise throws error and doesn't reject

如果其中有一个带有异步函数的 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/catched 以便 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 立即被拒绝。