Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I wait for a function to be called by an unknown caller?

I have a callback function that gets called by some other object which I can’t control. I need to wait until this callback function is called, I don’t care by who.

var successFunc = function() {
    // do stuff
}

myObject.onSuccess = successFunc;

// hang on until successFunc is called...

I found this hacky workaround, but it sucks:

var completed = false;

var successFunc = () => {
    // do stuff
    completed = true;
}

myObject.onSuccess = successFunc;

while (!completed) {
    sleep(200); // sleeps for 200 ms
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a promise, pass its resolve function as callback to the unknown caller somehow, listen to the promise’s resolution:

let callback;
const promise = new Promise(r => callback = r);

promise.then(() => console.log('unknown caller called'));

setTimeout(function unknownCaller() {
    console.log('randomly calling back');
    callback();
}, Math.random() * 5000);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading