lgwebdream/FE-Interview

Day95:Promise.all中任何一个Promise出现错误的时候都会执行reject,导致其它正常返回的数据也无法使用。你有什么解决办法么?

Opened this issue · 1 comments

Day95:Promise.all中任何一个Promise出现错误的时候都会执行reject,导致其它正常返回的数据也无法使用。你有什么解决办法么?

每日一题会在下午四点在交流群集中讨论,五点 Github、交流群同步更新答案

1)在单个的catch中对失败的promise请求做处理

2)把reject操作换成 resolve(new Error("自定义的error"))

3)引入Promise.allSettled

const promises = [
    fetch('/api1'),
    fetch('/api2'),
    fetch('/api3'),
  ];
  
  Promise.allSettled(promises).
    then((results) => results.forEach((result) => console.log(result.status)));
  // "fulfilled"
  // "fulfilled"
  // "rejected"

4)安装第三方库 promise-transaction

// 它是promise事物实现 不仅仅能处理错误还能回滚
  import Transaction from 'promise-transaction';
const t = new Transaction([
  {
    name: 'seed',
    perform: () => Promise.resolve(3),
    rollback: () => false,
    retries: 1, // optionally you can define how many retries you like to run if initial attemp fails for this step
  },
  {
    name: 'square',
    perform: (context) => {
      return Promise.resolve(context.data.seed * context.data.seed);
    },
    rollback: () => false,
  },
]);
 
return t.process().then((result) => {
  console.log(result); // should be value of 9 = 3 x 3
});