赞
踩
给出一个请求,这个请求可能失败也可能成功,如果失败了,就继续请求,如果超出最大请求次数
,就不再请求,如果成功,也不再请求
const allCount = 5; const fetchFn = () => { return new Promise((resolve, reject) => { console.log('请求啦,嘻嘻嘻'); setTimeout(() => { const n = Math.random(); n > 0.9 ? resolve() : reject('失败'); }, 500); }); }; const fetchNum = num => { if(num > allCount) { alert(`已经请求了${allCount}次啦,请求次数到达上限了`); return; } fetchFn() .then(res => { console.log('success', num); }) .catch(err => { console.log('err', num); fetchNum(num+1) }); }
const allCount = 5 const fetchFn = () => { return new Promise((resolve, reject) => { console.log('请求啦,嘻嘻嘻'); setTimeout(() => { const n = Math.random() n > 0.9 ? resolve() : reject('失败') }, 500) }) } const fetchNum = async num => { try { if(num > allCount) { alert(`已经请求了${allCount}次啦,请求次数到达上限了`) return } await fetchFn() console.log('success', num); }catch(err) { console.log('faild', num, err); await fetchNum(num+1) } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。