Polling function

const ServerMock = {
    
    
  count: 0,
  getData() {
    
    
    if (this.count === 2) {
    
    
      return Promise.resolve([{
    
     name: "SomeName" }]);
    } else {
    
    
      this.count++;
      return Promise.reject("Error");
    }
  }
};

function fetchData(limit, time) {
    
    
  return {
    
    
    then(resolve, reject) {
    
    
      const retry = setInterval(async () => {
    
    
        limit--;
        try {
    
    
          console.log("Trying....");
          const data = await ServerMock.getData();
          if (data) {
    
    
            console.log("Resolve");
            clearInterval(retry);
            resolve(data);
          }
        } catch {
    
    
          if (limit === 0) {
    
    
            clearInterval(retry);
            reject("Limit Reached");
          }
        }
      }, time);
    }
  };
}
// 轮询的时间为100,轮询的最大次数为3
(async () => {
    
    
  try {
    
    
    const result = await fetchData(3, 1000);
    console.log(result);
  } catch (err) {
    
    
    console.log(err);
  }
})();

The above is polling at intervals, we can also poll continuously instead of setting the interval

const ServerMock = {
    
    
  count: 0,
  getData() {
    
    
    console.log('调用')
    if (this.count === 2) {
    
    
      return Promise.resolve([{
    
     name: "SomeName" }]);
    } else {
    
    
      this.count++;
      return Promise.reject("Error");
    }
  }
};
const retry = (attempts, action) => {
    
    
  console.log('todo')
  const promise = action()
  return attempts > 0 ? promise.catch(() => retry(attempts - 1, action)) : promise
}

(async () => {
    
    
  let res = await retry(5, () => ServerMock.getData())
  console.log(res)
})

Guess you like

Origin blog.csdn.net/wu_xianqiang/article/details/108142239