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

Time:12-22

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
}

CodePudding user response:

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

CodePudding user response:

You can play with await/async:

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Operators/await

var myObject = {
    promiseCreation() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(true);
        }, 2000);
      });
    }
}

var successFunc = () => {
    completed = true;
    console.log('win');
};

myObject.onSuccess = successFunc;

var asyncfunc = async () => {
    var test = await myObject.promiseCreation();
    //do thing after promise resolved
    myObject.onSuccess();
}

asyncfunc();

CodePudding user response:

try settimeout function

setTimeout(() => {
        
      }, timeout);
  • Related