Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Genzhen opened this issue Jul 10, 2020 · 1 comment
Labels
JavaScript teach_tag

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Jul 10, 2020

No description provided.

@Genzhen Genzhen added the JavaScript teach_tag label Jul 10, 2020
@Genzhen
Copy link
Collaborator Author

Genzhen commented Jul 10, 2020

每日一题会在下午四点在交流群集中讨论,五点 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
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag
Projects
None yet
Development

No branches or pull requests

1 participant