在面试中,我们可能会遇到有面试官问如何使用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);
})