|
@@ -25,42 +25,33 @@ class MessageCenter {
|
|
|
}
|
|
|
|
|
|
listen(messageId, callback) {
|
|
|
- let activeQuene = this.messageCallbackMap.get(messageId);
|
|
|
- if (activeQuene?.length > 0) {
|
|
|
- activeQuene.push(callback)
|
|
|
- } else {
|
|
|
- this.messageCallbackMap.set(messageId, [callback])
|
|
|
- }
|
|
|
+ // 序列添加失败回调
|
|
|
+ this.messageCallbackMap.set(messageId, { callback })
|
|
|
}
|
|
|
|
|
|
addFailback(messageId, overTime = 2000, failback) {
|
|
|
- let failbackQuene = this.messageFailbackMap.get(messageId);
|
|
|
- if (failbackQuene && failbackQuene.failCallbackList) {
|
|
|
- failbackQuene.failCallbackList.push(
|
|
|
- failback
|
|
|
- )
|
|
|
- } else {
|
|
|
- this.messageFailbackMap.set(messageId, {
|
|
|
- time: new Date().getTime(),
|
|
|
- overTime,
|
|
|
- failCallbackList: [failback]
|
|
|
- })
|
|
|
- }
|
|
|
+ // 序列添加失败回调
|
|
|
+ this.messageFailbackMap.set(messageId, {
|
|
|
+ time: new Date().getTime(),
|
|
|
+ overTime,
|
|
|
+ failback
|
|
|
+ })
|
|
|
this.checkTimer()
|
|
|
}
|
|
|
|
|
|
-
|
|
|
-
|
|
|
init() {
|
|
|
window.addEventListener('message', (e) => {
|
|
|
const { info, data } = e.data;
|
|
|
+ // 序列删除 失败回调
|
|
|
this.messageFailbackMap.delete(info.messageId);
|
|
|
- const quene = this.messageCallbackMap.get(info.messageId) || [];
|
|
|
- let index = 0;
|
|
|
- while (index < quene.length) {
|
|
|
- const callback = quene[index];
|
|
|
+
|
|
|
+ // 执行成功回调
|
|
|
+ const _item = this.messageCallbackMap.get(info.messageId);
|
|
|
+ if (_item) {
|
|
|
+ const callback = _item.callback
|
|
|
callback(data)
|
|
|
- index++
|
|
|
+ // 序列删除 成功回调
|
|
|
+ this.messageCallbackMap.delete(info.messageId)
|
|
|
}
|
|
|
})
|
|
|
|
|
@@ -70,25 +61,26 @@ class MessageCenter {
|
|
|
if (this.timer) {
|
|
|
return
|
|
|
}
|
|
|
+ let key, value, now_time
|
|
|
this.timer = setInterval(() => {
|
|
|
- if (this.messageFailbackMap.values().length == 0) {
|
|
|
+ if (this.messageFailbackMap.size == 0) {
|
|
|
clearInterval(this.timer)
|
|
|
this.timer = null
|
|
|
}
|
|
|
|
|
|
// 轮询查看有无超期的message信息
|
|
|
- const now = new Date().getTime();
|
|
|
- for (let item of this.messageFailbackMap.values()) {
|
|
|
- if (now - item.time > item.overTime) {
|
|
|
- let index = 0;
|
|
|
- while (index < item.failCallbackList.length) {
|
|
|
- const callback = item.failCallbackList[index];
|
|
|
- callback({
|
|
|
- error: 0,
|
|
|
- msg: "message 超时错误"
|
|
|
- })
|
|
|
- index++
|
|
|
- }
|
|
|
+ now_time = new Date().getTime();
|
|
|
+ for (let item of this.messageFailbackMap.entries()) {
|
|
|
+ key = item[0] || ''
|
|
|
+ value = item[1] || {}
|
|
|
+
|
|
|
+ if (now_time - value.time > value.overTime) {
|
|
|
+ const callback = value.failback
|
|
|
+ callback && callback({
|
|
|
+ error: 0,
|
|
|
+ msg: "message 超时错误"
|
|
|
+ })
|
|
|
+ this.messageFailbackMap.delete(key)
|
|
|
}
|
|
|
}
|
|
|
}, 1000)
|