mirror of
https://github.com/KieSun/all-of-frontend.git
synced 2024-12-12 09:54:36 +08:00
feat: update answer
This commit is contained in:
parent
c89310f1d2
commit
c1cb5f8269
43
Answer/1 ~ 10/5.md
Normal file
43
Answer/1 ~ 10/5.md
Normal file
@ -0,0 +1,43 @@
|
||||
异步请求通过 `Promise.all` 处理,怎么让其中失败的所有请求重试。
|
||||
|
||||
```js
|
||||
Promise.all([A, B, C, D])
|
||||
// 4 个请求完成后发现 AD 请求失败了,如果让 AD 请求重试
|
||||
```
|
||||
|
||||
这个题目其实很简单,因为 `Promise.all` 中一个 `promise` 挂了就挂了,所以我们直接在接口上处理 `catch` 就行了。
|
||||
|
||||
看了些答案,结果是对的,但是处理方式是错误的。比如说在 `resolve` 中去判断是否要重试。一般我们业务中请求都是封装过的函数,出现错误肯定直接 `reject` 了,不可能 `resolve` 出来。
|
||||
|
||||
答案摘自 [vandvassily](https://github.com/KieSun/fucking-frontend/issues/6#issuecomment-797237791)
|
||||
|
||||
其他类似优秀答案:[yancongwen](https://github.com/KieSun/fucking-frontend/issues/6#issuecomment-797283287)
|
||||
|
||||
```js
|
||||
function request(name, count = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isSuccess = Math.random() > 0.5;
|
||||
console.log(`接口${name}: ${isSuccess}`);
|
||||
setTimeout(() => {
|
||||
isSuccess > 0.5 ? resolve(name) : reject(name);
|
||||
}, Math.random() * 1000);
|
||||
}).catch((err) => {
|
||||
count++;
|
||||
|
||||
if (count > 2) {
|
||||
return Promise.reject(`后端大爷${name}接口写的666`);
|
||||
}
|
||||
return request(name, count);
|
||||
});
|
||||
}
|
||||
|
||||
let queue = [request('A'), request('B'), request('C'), request('D')];
|
||||
|
||||
Promise.all(queue)
|
||||
.then((arr) => {
|
||||
console.log(arr);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
});
|
||||
```
|
Loading…
Reference in New Issue
Block a user