同时请求多个接口需要注意的地方,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  使用方式 大家搜搜就晓得啦

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/130937175