方法封装
首先新建 haveload.js ,文件中对Ajax请求进行二次封装,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import request from '@/utils/request'
export function retryServerGet(url, maxCount = 1, params = {}) { return new Promise((resolve, reject) => { request .get(url, {params}) .then(res => { resolve(res) }) .catch(err => { maxCount <= 1 ? reject(err) : retryServerGet(url, maxCount - 1, params) }) }) }
export function retryServerPost(url, maxCount = 1, data = null) { return new Promise((resolve, reject) => { request .post(url, data) .then(res => { console.log(res) resolve(res) }) .catch(err => { maxCount <= 1 ? reject(err) : retryServerPost(url, maxCount - 1, data) }) }) }
|
上面代码中有两个方法,分别对 get 请求和 post 请求做处理,这两个方法都接收三个参数:
- 第一个参数url:表示请求接口的地址
- 第二个参数maxCount:最大请求次数,比如接口想请求5次,如果5次请求中有一次成功了,则不会继续往后请求,会把成功的结果返回
- 第三个参数:接口请求所携带的参数
使用方法
在文件中引入上面的文件,然后编写自定义方法并导出
1 2 3 4 5 6 7 8 9
| export function testGet1(params) { return retryServerGet(`/home/getTotalSalesAndIndextest`, 3, params) }
export function testPost() { return retryServerPost(`/api/custom/conversions`, 3, null) }
|
调用
1 2 3
| testGet1({year: 2022}).then(res => { console.log(res, '222222222') })
|
我这里的get请求地址并不存在,但是我让他循环3次重复调用,来看运行结果是什么

在控制台连续输出了三次404,如果把地址改成正常的,则效果如下

通过查看请求发现接口只调用了一次,并吧结果返回