简体   繁体   English

如果每个promise已经有一个catch块,则抛出Promise.all([])catch块?

[英]Throwing to Promise.all([]) catch block if each promise already has a catch block?

I thought that this would throw an error in the Promise.all catch block, but it never gets that far? 我以为这会在Promise.all catch块中引发错误,但是它永远不会Promise.all那么远?

I'm trying to understand how I can handle the rejected promise at the call and also at Promise.all . 我试图了解如何处理电话和Promise.all被拒绝的承诺。

const apiCallOne = new Promise((resolve, reject) => (
  resolve('Resolved !!!')
)).then(console.log)
  .catch(console.warn);

const apiCallTwo = new Promise((resolve, reject) => (
  reject('Rejected !!!')
)).then(console.log)
  .catch(console.warn);

Promise.all([apiCallOne, apiCallTwo])
  .then(value => console.log('all', value))
  .catch(err => console.error('error', err));

Will Promise.all ever hit it's catch block? Promise.all会碰到它的障碍吗?

No it won't the catch will swallow the errors and like you said Promise.all catch block will never be called, the following will work according to your expectations 不,它不会使catch吞没错误,就像您所说的Promise.all catch块将永远不会被调用,以下将根据您的期望工作

const apiCallOne = new Promise((resolve, reject) => (
  resolve('Resolved !!!')
)).then(console.log)
  .catch((err) => {
    console.warn(err)
    throw err
  });

const apiCallTwo = new Promise((resolve, reject) => (
  reject('Rejected !!!')
)).then(console.log)
  .catch((err) => {
    console.warn(err)
    throw err
  });

Promise.all([apiCallOne, apiCallTwo])
  .then(value => console.log('all', value))
  .catch(err => console.error('error', err));

You can handle them when you call Promise.all , there is no need to handle them before you execute the requests because we want to run them in parallel and cancel all if there is an error. 您可以在调用Promise.all时处理它们,无需在执行请求之前处理它们,因为我们希望并行运行它们,并在出现错误时将其全部取消。

const apiCallOne = new Promise((resolve, reject) => (
  resolve('Resolved !!!')
))

const apiCallTwo = new Promise((resolve, reject) => (
  reject('Rejected !!!')
))

Promise.all([apiCallOne, apiCallTwo])
  .then(value => console.log('all', value))
  .catch(err => console.error('error', err));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM