2022-01-21 08:28:41 +00:00
|
|
|
import { Action } from './Action';
|
|
|
|
export class AsyncAction extends Action {
|
|
|
|
constructor(scheduler, work) {
|
|
|
|
super(scheduler, work);
|
|
|
|
this.scheduler = scheduler;
|
|
|
|
this.work = work;
|
|
|
|
this.pending = false;
|
|
|
|
}
|
|
|
|
schedule(state, delay = 0) {
|
|
|
|
if (this.closed) {
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
this.state = state;
|
|
|
|
const id = this.id;
|
|
|
|
const scheduler = this.scheduler;
|
|
|
|
if (id != null) {
|
|
|
|
this.id = this.recycleAsyncId(scheduler, id, delay);
|
|
|
|
}
|
|
|
|
this.pending = true;
|
|
|
|
this.delay = delay;
|
|
|
|
this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
|
|
|
|
return this;
|
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
requestAsyncId(scheduler, id, delay = 0) {
|
|
|
|
return setInterval(scheduler.flush.bind(scheduler, this), delay);
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
recycleAsyncId(scheduler, id, delay = 0) {
|
|
|
|
if (delay !== null && this.delay === delay && this.pending === false) {
|
2022-01-21 08:28:41 +00:00
|
|
|
return id;
|
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
clearInterval(id);
|
2022-01-21 08:28:41 +00:00
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
execute(state, delay) {
|
|
|
|
if (this.closed) {
|
|
|
|
return new Error('executing a cancelled action');
|
|
|
|
}
|
|
|
|
this.pending = false;
|
|
|
|
const error = this._execute(state, delay);
|
|
|
|
if (error) {
|
|
|
|
return error;
|
|
|
|
}
|
|
|
|
else if (this.pending === false && this.id != null) {
|
|
|
|
this.id = this.recycleAsyncId(this.scheduler, this.id, null);
|
|
|
|
}
|
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
_execute(state, delay) {
|
2022-01-21 08:28:41 +00:00
|
|
|
let errored = false;
|
2022-05-29 09:24:36 +00:00
|
|
|
let errorValue = undefined;
|
2022-01-21 08:28:41 +00:00
|
|
|
try {
|
|
|
|
this.work(state);
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
errored = true;
|
2022-05-29 09:24:36 +00:00
|
|
|
errorValue = !!e && e || new Error(e);
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
if (errored) {
|
|
|
|
this.unsubscribe();
|
|
|
|
return errorValue;
|
|
|
|
}
|
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
_unsubscribe() {
|
|
|
|
const id = this.id;
|
|
|
|
const scheduler = this.scheduler;
|
|
|
|
const actions = scheduler.actions;
|
|
|
|
const index = actions.indexOf(this);
|
|
|
|
this.work = null;
|
|
|
|
this.state = null;
|
|
|
|
this.pending = false;
|
|
|
|
this.scheduler = null;
|
|
|
|
if (index !== -1) {
|
|
|
|
actions.splice(index, 1);
|
|
|
|
}
|
|
|
|
if (id != null) {
|
|
|
|
this.id = this.recycleAsyncId(scheduler, id, null);
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
2022-05-29 09:24:36 +00:00
|
|
|
this.delay = null;
|
2022-01-21 08:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
//# sourceMappingURL=AsyncAction.js.map
|