如果您在一个承诺中有一个承诺,是否需要两个陷阱?

问题描述 投票:0回答:1

例如,使用fetch()进行两次呼叫(.then()内部的第二个呼叫,您是否需要两个.catch()还是仅外部一个就足够了?

我已经尝试复制,但到目前为止还不能。

b = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('Solving...');
    resolve('solved');
  }, 3000);
})
  .then(() => {
    new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('Rejecting...');
        reject('error');
      }, 1000);
    })
      .then(() => null)
      .catch((error) => {
        console.log('Catching error inside.');
        console.log(error);
      });
  })
  .catch((error) => {
    console.log('Catching error outside.');
    console.log(error);
  });

此方法有效,但是如果删除内部的catch(),则会出现Unhandled promise rejection错误

Solving...
Rejecting...
(node:73650) UnhandledPromiseRejectionWarning: error
(node:73650) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:73650) [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.
javascript fetch es6-promise
1个回答
0
投票

不需要多个catch()。如果检测到任何错误,则转到catch()

© www.soinside.com 2019 - 2024. All rights reserved.