CEC-5182: add car update status to fleet (#466)
This commit is contained in:
29
src/utils/polling.js
Normal file
29
src/utils/polling.js
Normal file
@@ -0,0 +1,29 @@
|
||||
export default class Polling {
|
||||
constructor(callback = () => Promise.resolve(), duration = 1000) {
|
||||
this.callback = callback;
|
||||
this.duration = duration;
|
||||
this.timeout = undefined;
|
||||
}
|
||||
|
||||
#sleep() {
|
||||
this.end();
|
||||
return new Promise((resolve) => {
|
||||
this.timeout = setTimeout(resolve, this.duration);
|
||||
});
|
||||
}
|
||||
|
||||
async start(payload) {
|
||||
this.callback(payload)
|
||||
.then(() => {
|
||||
this.#sleep().then(() => this.start(payload));
|
||||
});
|
||||
}
|
||||
|
||||
end() {
|
||||
if (!this.timeout) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(this.timeout);
|
||||
}
|
||||
}
|
||||
31
src/utils/polling.test.js
Normal file
31
src/utils/polling.test.js
Normal file
@@ -0,0 +1,31 @@
|
||||
import Polling from "./polling";
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
describe("Polling", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("starts and ends polling", async () => {
|
||||
const callback = () => Promise.resolve();
|
||||
const poll = new Polling(callback, 100);
|
||||
const spy = jest.spyOn(poll, "callback");
|
||||
poll.start();
|
||||
await sleep(500);
|
||||
poll.end();
|
||||
await sleep(500);
|
||||
expect(spy).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it("async polling", async () => {
|
||||
const callback = () => sleep(100);
|
||||
const poll = new Polling(callback, 100);
|
||||
const spy = jest.spyOn(poll, "callback");
|
||||
poll.start();
|
||||
await sleep(1000);
|
||||
expect(spy).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user