如何等待未知调用者调用函数?

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

我有一个回调函数,它被我无法控制的其他对象调用。我需要等到这个回调函数被调用,我不关心被谁调用。

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

myObject.onSuccess = successFunc;

// hang on until successFunc is called...

我发现了这个 hacky 解决方法,但它很糟糕:

var completed = false;

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

myObject.onSuccess = successFunc;

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

创建一个承诺,以某种方式将其 resolve 函数作为回调传递给未知调用者,听取承诺的解决方案:

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