Change FrontendApiSender.callbacks to be a map

This commit is contained in:
toasted-nutbread 2019-12-21 14:30:13 -05:00
parent a2175f2c29
commit 362e317a5d

View File

@ -22,7 +22,7 @@ class FrontendApiSender {
this.senderId = FrontendApiSender.generateId(16); this.senderId = FrontendApiSender.generateId(16);
this.ackTimeout = 3000; // 3 seconds this.ackTimeout = 3000; // 3 seconds
this.responseTimeout = 10000; // 10 seconds this.responseTimeout = 10000; // 10 seconds
this.callbacks = {}; this.callbacks = new Map();
this.disconnected = false; this.disconnected = false;
this.nextId = 0; this.nextId = 0;
@ -43,7 +43,7 @@ class FrontendApiSender {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const info = {id, resolve, reject, ack: false, timer: null}; const info = {id, resolve, reject, ack: false, timer: null};
this.callbacks[id] = info; this.callbacks.set(id, info);
info.timer = setTimeout(() => this.onError(id, 'Timeout (ack)'), this.ackTimeout); info.timer = setTimeout(() => this.onError(id, 'Timeout (ack)'), this.ackTimeout);
this.port.postMessage({id, action, params, target, senderId: this.senderId}); this.port.postMessage({id, action, params, target, senderId: this.senderId});
@ -71,19 +71,18 @@ class FrontendApiSender {
onDisconnect() { onDisconnect() {
this.disconnected = true; this.disconnected = true;
const ids = Object.keys(this.callbacks); for (const id of this.callbacks.keys()) {
for (const id of ids) {
this.onError(id, 'Disconnected'); this.onError(id, 'Disconnected');
} }
} }
onAck(id) { onAck(id) {
if (!hasOwn(this.callbacks, id)) { const info = this.callbacks.get(id);
if (typeof info === 'undefined') {
console.warn(`ID ${id} not found for ack`); console.warn(`ID ${id} not found for ack`);
return; return;
} }
const info = this.callbacks[id];
if (info.ack) { if (info.ack) {
console.warn(`Request ${id} already ack'd`); console.warn(`Request ${id} already ack'd`);
return; return;
@ -95,18 +94,18 @@ class FrontendApiSender {
} }
onResult(id, data) { onResult(id, data) {
if (!hasOwn(this.callbacks, id)) { const info = this.callbacks.get(id);
if (typeof info === 'undefined') {
console.warn(`ID ${id} not found`); console.warn(`ID ${id} not found`);
return; return;
} }
const info = this.callbacks[id];
if (!info.ack) { if (!info.ack) {
console.warn(`Request ${id} not ack'd`); console.warn(`Request ${id} not ack'd`);
return; return;
} }
delete this.callbacks[id]; this.callbacks.delete(id);
clearTimeout(info.timer); clearTimeout(info.timer);
info.timer = null; info.timer = null;
@ -118,9 +117,9 @@ class FrontendApiSender {
} }
onError(id, reason) { onError(id, reason) {
if (!hasOwn(this.callbacks, id)) { return; } const info = this.callbacks.get(id);
const info = this.callbacks[id]; if (typeof info === 'undefined') { return; }
delete this.callbacks[id]; this.callbacks.delete(id);
info.timer = null; info.timer = null;
info.reject(new Error(reason)); info.reject(new Error(reason));
} }