interface Option { fun: Function param?: any interval?: number callback: Function errorCallback?: Function } class Polling { version = '0.0.1' timer: any config = { interval: 5000, store: {}, } options: Option = { fun: () => {}, callback: () => {} } isDestroy = false constructor (fun, param, interval, callback, errorCallback?) { this.options = { fun, param, interval, callback, errorCallback } this.run(this.options) } async run ({ fun, param, interval, callback, errorCallback }: Option) { let success let fail try { success = await fun(param) } catch (e) { fail = e } // 成功 if (success && callback) { await callback(success, fail) } // 失败 if (fail && errorCallback) { console.error('Polling ERROR:', fail) await errorCallback(fail) } if (this.isDestroy) return clearTimeout(this.timer) this.timer = setTimeout(() => { this.run({ fun, param, interval, callback, errorCallback }) }, interval) } stop () { clearTimeout(this.timer) this.isDestroy = true } continue () { if (this.isDestroy && this.options.param) { this.isDestroy = false this.run(this.options) } } /** * 更新轮询参数,必须先stop,再update,之后continue * @param newOptions 新的轮询参数 */ updateOptions (newOptions) { if (!this.isDestroy) return this.options = Object.assign({}, this.options, newOptions) } } export default Polling