【发布时间】:2020-12-28 16:16:40
【问题描述】:
我正在尝试将回调函数转换为异步/等待。该代码使用从主窗口框架到 iframe 的 postMessage。当 iframe 发回消息时,它会调用回调函数。有什么方法可以从$(window).on(...) 模式转换为 Promise?
工作代码的最小版本:
调用函数:
window.bridge.post(cb);
桥对象:
class Bridge {
constructor(win, root) {
this.win = win;
this.root = root;
this.bindEvents();
this.post = this.factoryMethod('post', 'postResult');
}
post(eventName, paramObject) {
this.win.postMessage([eventName, JSON.stringify(paramObject)], this.root);
}
bindEvents() {
window.addEventListener('message', e => this.handleEvents(e));
}
handleEvents(e) {
const eventName = e.data[0];
const eventObj = e.data[1];
if (typeof eventName !== 'undefined' && eventName != null) {
$(window).trigger(eventName, eventObj);
}
}
factoryMethod(msgIn, msgOut) {
return (cb) => {
this.post(msgIn, {});
$(window).on(msgOut, (e, arg) => cb(arg));
};
}
}
export default Bridge;
提前致谢。
【问题讨论】:
-
new Promise(resolve => $(window).once(msgOut, resolve))? -
是
once还是on?这会允许window.bridge.post().then(fun)吗?我认为 post 函数必须返回一个 Promise 对吗? -
once- 承诺只能一次结算,对于多条消息,您需要单独的承诺。这就是为什么它们不太适合事件流的原因。如果你允许异步并发消息传递,无论如何它会变得复杂得多。
标签: javascript jquery asynchronous iframe