我正在尝试将回调函数转换为异步/等待。该代码使用从主窗口框架到 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;
提前致谢。
最佳答案
感谢 Bergi 的评论,我能够将其转换为 Promise。
factoryMethod(msgIn, msgOut) {
return (ann) => new Promise((resolve, reject) => {
this.post(msgIn, ann);
$(window).on(msgOut, (e, arg) => resolve(arg));
});
}
这会返回一个返回 Promise 的高阶函数。
关于javascript - 如何将触发器/事件转换为 Promise 或异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43929979/