async await实践

现在有这样一个需求,有四个请求同时发出,如果有某个出错了,如果总次数少于10次,我就重新请求

let num = 0;
let res = void 0;
function reqs() {
  let pro1 = new Promise((res, rej) => {
    res(fetch('http://localhost:8080')); 
  });
  let pro2 = new Promise((res, rej) => {
    res(fetch('http://localhost:8080'));
  });

  let pro3 = new Promise((res, rej) => {
    res(fetch('http://localhost:8080'));
  });

  let pro4 = new Promise((res, rej) => {
    res(fetch('http://localhost:8080'));
  });

  // Promise.all, 如果有出现, 立马会执行catch,但是其它请求还是会发送
  Promise.all([pro1, pro2, pro2, pro4]).then((response)=>{
    res = response;
  }).catch((err) => {
    if(num <= 10) {
      num ++;
      reqs();
    }else {
      res = 'error';
    }
  });
}

reqs();

let count = 0;
let res = void 0;
async function request() {
  //throw Error('err');
   res = await fetch('http://localhost:8080', {
    method: 'GET',
  }).then((res) => res).catch((err)=>'error');
  console.log(res, count);
  while(res === 'error' && count <= 10) {
    res = await fetch('http://localhost:8080').then((res) => res).catch((err)=>'error');
    count ++;
    console.log(res, count);
  }
  if(count > 10) {
    console.log('提醒用户请求多次仍然无果');
    return 'server no answer';
  }else return res;
}
console.log('加loading效果');
request().then((res) => {console.log('关loading');console.log(res);}).catch((err) => {console.log('关loading');console.log('err');});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值