同时请求多个接口需要注意的地方,promise.all 和promise.allSettled

假设有以下两个请求接口:

const reasult1 = await this.fetch('https://api/xxxxxxxxxxx/xxx')
const reasult2 = await this.fetch('https://api/yyyyyy/yyyyyy')

//假设一种情况,就是必须两个接口都请求的条件场景的时候,就需要用到Promise.all

const result = await Promise.all([
                await this.fetch('https://api/xxxxxxxxxxx/xxx'),
                await this.fetch('https://api/yyyyyy/yyyyyy'),
            ])

//到这里需要注意的是,请求是有可能报错的,当promise.all里面任意一个接口报错,就会程序崩溃,因为并没有catch,所以下面有两种方式catch 错误

//第一种

const result = await Promise.all([
                await this.fetch('https://api/xxxxxxxxxxx/xxx'),
                await this.fetch('https://api/yyyyyy/yyyyyy'),
            ].map(item=>item.catch(e=>console.log(e))))

//第二种  :Promise.allSettled  使用方式 大家搜搜就晓得啦

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Promise.all和Promise.allSettled是两种不同的Promise方法,它们在使用场景和返回结果上有所不同。 1. Promise.all: - 使用场景:当需要等待多个Promise对象都完成后再执行后续操作时,可以使用Promise.all。 - 返回结果:返回一个新的Promise对象,Promise对象在所有给定的Promise对象都已经fulfilled后才fulfilled,如果其中任何一个Promise对象被rejected,则返回的Promise对象立即被rejected。 - 示例代码: ```javascript const promise1 = Promise.resolve(1); const promise2 = Promise.resolve(2); const promise3 = Promise.resolve(3); Promise.all([promise1, promise2, promise3]) .then(values => { console.log(values); // 输出:[1, 2, 3] }) .catch(error => { console.log(error); // 如果有任何一个Promise对象被rejected,则执行这里的代码 }); ``` 2. Promise.allSettled: - 使用场景:当需要等待多个Promise对象都完成后,无论是fulfilled还是rejected,都需要获取每个Promise对象的结果时,可以使用Promise.allSettled。 - 返回结果:返回一个新的Promise对象,该Promise对象在所有给定的Promise对象都已经fulfilled或rejected后才fulfilled,返回的Promise对象带有一个对象数组,每个对象表示对应的Promise对象的结果,包括状态(fulfilled或rejected)和值。 - 示例代码: ```javascript const apiOne = function(id) { return new Promise((resolve, reject) => { resolve({ result: true, text: 1 }); }); }; const apiTwo = function(id) { return new Promise((resolve, reject) => { reject({ result: true, text: 2 }); }); }; Promise.allSettled([apiOne('one'), apiTwo('two')]) .then(results => { console.log(results); /* 输出: [ { status: 'fulfilled', value: { result: true, text: 1 } }, { status: 'rejected', reason: { result: true, text: 2 } } ] */ }) .catch(error => { console.log(error); }); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柑橘乌云_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值