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.
To convert a callback into a promise, you need to return a promise. You run the code with the callback inside the promise. const readFilePromise = () => { return new Promise((resolve, reject) => { fs. readFile(filePath, options, (err, data) => { // ... }) }) }
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
If you need to access an event in an asynchronous way, then you should call event. persist() at the beginning of the function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With