1

I want to :

  1. wait until a function A is defined (it's in a file loaded asynchronusly)
  2. then run function B
  3. and i'd like to create a generic wrapper for that, so that i can directly make something like waitFor(functionToWait, functionToExecute)

    • i have a result for part 1 & 2, but it's based on setTimeout/setInterval, but i'd like to know if there would be a more elegant way (something like a watcher on the waited function)
    • and i have no idea on the second part, especially how to use a string parameter to convert it into a function reference.

Thanks

MarvinLeRouge
  • 444
  • 5
  • 15

1 Answers1

2

My answer is a combination of the answers from: What is the JavaScript version of sleep()? and: How to check if function exists in JavaScript?

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function demo(cb) {
        while(typeof A !== "function") {
            await sleep(1000);
        }
        cb();
    }

    demo(function() { console.log("function A exists"); });

    var A = function() { };
de-facto
  • 283
  • 2
  • 8