promise中的异步函数会引发错误并且不会拒绝

时间:2019-02-09 22:26:14

标签: javascript asynchronous error-handling promise catch-block

如果其中有一个带有异步函数的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);
});

1 个答案:

答案 0 :(得分:3)

Promise构造函数内引发并异步发生的错误必须明确地try / catch处理,以便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立即被拒绝。