代码之家  ›  专栏  ›  技术社区  ›  Andrey Bushman

为什么我会收到针对已处理错误的“(节点:7424)unhandledPromisejectionWarning”消息?

  •  0
  • Andrey Bushman  · 技术社区  · 6 年前

    我以诚实的态度对待我承诺中的错误 catch ,但在Node.js(v10.11.0)控制台输出中,我看到了以下消息: (node:7424) UnhandledPromiseRejectionWarning: Error: Oops..

    // See browser console, not stack snippet console, to see uncaught error
    
    const p = new Promise((resolve,reject) => { throw new Error('Oops..');});
    
    p.then(()=> console.log('Then'));
    p.catch(err => console.log(err.message)); // the error handling
    
    console.log('The end');

    同样,对于这样的变量,我得到了相同的结果 p 初始化:

    const p = new Promise((resolve,reject) => { reject(new Error('Oops..'));});
    

    这是我的输出:

    结局

    (节点:7492)未处理的PromisejectionWarning:错误:Oops。。

    1 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    无论你什么时候打电话 .then .catch )在现有的承诺上,您有一个 Promise . 错误源于由创建的承诺链

    p.then(()=> console.log('Then'));
    

    在任何地方都不会被抓到。

    要么是链条 接住 然后 :

    const p = new Promise((resolve, reject) => {
      throw new Error('Oops..');
    });
    
    p
      .then(() => console.log('Then'))
      .catch(err => console.log(err.message));
    
    console.log('The end');

    reject 当出现错误时,请明确说明,以确保该承诺的消费者能够发现问题。例如,在下面的代码中 p 将被拒绝,并且将永远无法解决,因为错误是异步抛出的:

    const p = new Promise((resolve, reject) => {
      setTimeout(() => {
        throw new Error('Oops..');
      });
    })
    
    p
      .then(() => console.log('Then'))
      .catch(err => console.log(err.message))
    
    console.log('The end');

    最好打电话 拒绝 :

    const p = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject('Oops..');
      });
    })
    
    p
      .then(() => console.log('Then'))
      .catch(err => console.log(err))
    
    console.log('The end');