面试时,问如何使用promise同时发送多个请求

在面试中,我们可能会遇到有面试官问如何使用promise同时发送多个请求,解析来啦

        :浏览器的内核与版本不同,支持并发的数量不同,比如:谷歌支持6个和8个,火狐支持3个和6个,而低版本的IE浏览器仅支持3个,在请求数量多的情况下,我们如果使用Promise.all方法的话,会出现请求丢失。请求阻塞问题。如果使用Promise的.then()方法的话,请求会一个一个发送,会出现请求时间过长的问题。根据以上这些情况,我们可以找到浏览器的安全并发数字为3和4,可使用二维数组将请求分为3个一组或4个一组,利用Promise.all方法与.then()方法相结合,进行分片并发请求。

代码解析:

分别使用以上三种方式,进行对比。

假设:我需要同时发送10个请求,如何防止丢失请求或者请求阻塞问题?还能完成性能优化。

        先写一段promise代码:

function axios() {
    return new Promise((resolve, reject) => {
        console.log('开始发送请求');
        setTimeout(() => {
            console.log('服务器响应了---------');
            resolve('结果')
        }, 1000);
    })
}

我们有三种方案:

方案一:使用Promise.all()

let tasts = [axios(),axios(),axios(),axios(),axios(),axios(),axios(),axios(),axios(),axios()];
// 使用这种方式,会出现请求丢失,请求堵塞的问题
Promise.all(tasts).then(res=>{
    console.log(res);
})

方案二:使用.then()

        优势:与方案一相比较,此方案会请求成功

        弊端:请求时间太长。。。

axios().then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
}).then(res=>{
    return axios()
})

方案三:Promise.all方法与.then()方法相结合,可以叫做 分片并发上传 (最优解)

let arr= [
    [axios(),axios(),axios()],
    [axios(),axios(),axios(),axios()],
    [axios(),axios(),axios()],
]

let result = []
Promise.all(arr[0]).then(res=>{
    result = result.concat(res)
    return Promise.all(arr[1])
}).then(res=>{
    result = result.concat(res)
    return Promise.all(arr[2])
}).then(res=>{
    result = result.concat(res);
    console.log(result);
})

  • 10
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值