[js] 写一个方法实现promise失败后自动重试
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head><body></body></html>
<script>Promise.retry = (fun, limit = 5) => {return new Promise((resolve, reject) => {let __num = 1;let __run = () => {fun().then(res => {resolve(res);}).catch(err => {if (__num++ >= limit) {reject(err)} else {console.log('retry again!!')__run()}})}__run()})}let k = 0function test() {return new Promise((resolve, reject) => {if (++k >= 3) {resolve(k)} else {reject('hhh')}})}Promise.retry(test).then(res => {console.log('resolve: ', res)}).catch(err => {console.log('reject: ', err)})// retry again!!// retry again!!// resolve: 3
</script>
运行结果
个人简介
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论
主目录
与歌谣一起通关前端面试题