如何将触发器/事件转换为 Promise 或 async/await?

Ric*_*Han 6 javascript iframe jquery asynchronous

我正在尝试将回调函数转换为 async/await。该代码使用从主窗口框架到 iframe 的 postMessage。当 iframe 回发消息时,它会调用回调函数。有什么方法可以从$(window).on(...)模式转换为 Promise吗?

工作代码的最小版本:

调用函数:

window.bridge.post(cb);
Run Code Online (Sandbox Code Playgroud)

桥梁对象:

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;
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Ric*_*Han 6

感谢 Bergi 的评论,我能够将其转换为 Promise。

factoryMethod(msgIn, msgOut) {                                                                                                                                                                                  
  return (ann)  => new Promise((resolve, reject) => {                        
    this.post(msgIn, ann);                                                                                                                                                                                      
    $(window).on(msgOut, (e, arg) => resolve(arg));                                                                                                           
  });                                                                                                                                                                                                           
}    
Run Code Online (Sandbox Code Playgroud)

这将返回一个返回 Promise 的高阶函数。