Skip to content

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
}

Answer

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);