javascript - 如何将触发器/事件转换为 Promise 或异步/等待?

标签 javascript jquery asynchronous iframe

我正在尝试将回调函数转换为异步/等待。该代码使用从主窗口框架到 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/

相关文章:

jquery - 从 WebForm 代码隐藏中使用 JQuery 更改 CSS

javascript - 如何中断nodejs中超时长时间运行的方法?

javascript - 如何在不嵌套回调的情况下保证同步执行?

javascript - PhoneGap 新手,需要入门指导

javascript - 在 Jest 中使用正则表达式和 toHaveProperty()

java - 我在这里缺少什么?

jQuery 浮点 : reapeating labels on x-axis

javascript - 范围编译后如何运行 Controller 代码

javascript - d3.json : "Uncaught TypeError: Cannot read property ' children' of undefined"

javascript - 错误: Failed to lookup view "index" in views directory "public"