async 函数实现轮询机制,简单易懂

2,643 阅读1分钟

今天分享一下js 轮询机制实现,简单易懂,30行代码搞定

之前一直使用saga的rece机制实现轮询,感觉代码冗余挺多的,就手敲一个

直接上到核心代码 26行搞定

const delay = duration =>
  new Promise((res, rej) => {
    setTimeout(() => {
      res();
    }, duration);
  });
class Polling {
  constructor(duration = 10000, stopPollingFlag = false) {
    this.duration = duration;
    this.stopPollingFlag = stopPollingFlag;
  }
  startPolling = async ({ apiFn, apiArgs, apiCallback }) => {
    while (!this.stopPollingFlag) {
      await delay(this.duration);
      if (this.stopPollingFlag) break;
      const data = await apiFn(apiArgs);
      if (this.stopPollingFlag) break;
      apiCallback(data);
    }
  };
  stopPolling() {
    this.stopPollingFlag = true;
  }
}

export default Polling;

使用

直接上代码

import Polling from "Polling";
 let polling = new Polling();
 const apiCallback =(res)=>{
    console.log(res)
 }
const startPolling({reStart}){
    if(reStart){
     polling.stopPolling()
     polling = new Polling(); 
    }
   
    polling.startPolling({
      apiFn: getADList,
      apiArgs: {
        code,
        currency,
        direction,
        page_num,
        page_size
      },
      apiCallback: getPollingData
    });
}


简单粗暴,直接可以轮询起来