date: 2020-07-13 20:26
    title: [day95]Promise.all?

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

    1)在单个的catch中对失败的promise请求做处理
    2)把reject操作换成 resolve(new Error(“自定义的error”))
    3)引入Promise.allSettled

    1. const promises = [
    2. fetch('/api1'),
    3. fetch('/api2'),
    4. fetch('/api3'),
    5. ];
    6. Promise.allSettled(promises).
    7. then((results) => results.forEach((result) => console.log(result.status)));
    8. // "fulfilled"

    4)安装第三方库 promise-transaction

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