Novastorm
Novastorm

Reputation: 1458

Forcing a block on javascript

I have 2 global variables (left and right) which is set to "" when the page loads. I have 2 functions, one function deals with setting a value in left and right, and the other depends on the first function completing.

When running under normal conditions it is hit or miss whether that first function is able to load first. I've written some code to try and force it but it keeps falling into an infinite loop:

var done = false;
function block() {
        console.log("blocking");
        loadSelected();
    }

    function loadSelected() {
            ServerRun.getSource(AUTHTOKEN, function (a) {
                theSource = a[0];
                ServerRun.getObject(AUTHTOKEN, theSource, function (b) {
                    theObject = b[0];
                    ServerRun.getCounter(AUTHTOKEN, theSource, theObject, function (c) {
                        theCounter = c[0];
                        ServerRun.getAlerts(AUTHTOKEN, theSource, theObject, theCounter, function (d) {
                            leftSelected = d[0];
                            rightSelected = d[1];
                            console.log("Success!!!");
                            done = true;
                        });
                    });
                });
            });

            if (done == false)
            {
                block();
            }
            console.log(done);
            setCharts();
    }

I need to block all code execution as a lot of other methods are dependent on left and right having values. How can I stop execution until the loadSelected method has completed? I'm unsure if blocking it in this way is reliable.

Upvotes: 0

Views: 304

Answers (1)

Tivie
Tivie

Reputation: 18933

Blocking the execution is usually a bad idea.

Since B depends on A, you should run A first and then notify B that A has the value it needs.

You can do that with 2 similar techniques:

  • Callback: When A finishes, it runs a callback that updates B
  • Promises: A returns a promise that is passed to B. When A finishes, the promise is resolved and B is updated.

Reference

Upvotes: 1

Related Questions