代码之家  ›  专栏  ›  技术社区  ›  Sharcoux

未处理的拒绝承诺尽管抓住了承诺

  •  1
  • Sharcoux  · 技术社区  · 7 年前

    我不明白。。。是我还是节点中的一个bug?

    这和预期的一样好:

    const a = new Promise((resolve, reject) => {
      setTimeout(() => reject('timeout'), 1000);
    });
    a.catch(console.log);
    

    这是一个警告:

    const a = new Promise((resolve, reject) => {
      setTimeout(() => reject('timeout'), 1000);
    });
    a.then(console.log);
    a.catch(console.log);
    

    我明白了

    timeout
    (node:40463) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): timeout
    (node:40463) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   Fábio Peres Toi    7 年前

    使用 .then(...) 用一个承诺返回一个新的承诺(即 chaining ). 因此,当你做以下事情时:

    a.then(console.log); // line 1 creates a new promise "b"
    a.catch(console.log); // line 2 handles rejection on promise "a"
    

    哪里 a 是您最初的承诺,您正在第1行创建一个新的承诺(不是的承诺) 不再。我们就叫它吧 b .catch(...) ,这解释了您在控制台上看到的消息。

    要避免此消息,应添加 .catch(…) 为了这个新的承诺 b

        2
  •  5
  •   Andrii Muzalevskyi    7 年前

    注释和稍加修改的来源:

    // promise A is created
    const a = new Promise((resolve, reject) => {
      setTimeout(() => reject('timeout'), 1000);
    });
    
    // promise A is chained with .then()
    // means new promise is created
    // and only resolve catched here
    const aThenPromise = a.then(console.log);
    
    // promise A is chained with .catch()
    // means new promise is created
    // and only reject catched here
    const aCatchPromise = a.catch(console.log);
    
    // aThenPromise !== aCatchPromise
    

    什么时候答应 a

    • aCatchPromise 按预期工作,以及 timeout
    • aThenPromise 什么都不做,因为它只对 resolve() ,拒绝通过它,而不进行处理 因为这是不同的承诺 . 这会导致 UnhandledRejection

    无神论 ,

    一个可能的选择是 a.then(console.log).catch(console.log) 这将处理通过的拒绝 .then

        3
  •  -3
  •   Rex    7 年前

    a.then(console.log).catch(console.log);

    推荐文章