How to convert trigger/event into Promise or async/await?
asynchronous, iframe, javascript, jquery
Solution
Thanks to Bergi's comment I am able to convert it to Promise.
factoryMethod(msgIn, msgOut) {
return (ann) => new Promise((resolve, reject) => {
this.post(msgIn, ann);
$(window).on(msgOut, (e, arg) => resolve(arg));
});
}
This returns a higher order function that returns a Promise.
Problem
I am trying to convert a callback function to async/await. The code uses postMessage from the main window frame to an iframe. When the iframe posts a message back, it calls the callback function. Is there any way to convert to Promise from the `$(window).on(...)` pattern? Minimal version of working code: To call the function: ``` window.bridge.post(cb); ``` Bridge object: ``` 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; ``` Thanks in advance.