0

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.

1
  • 1
    you not need block, you can just use pomise, or, if you reaaly want block - just use sync request in ServerRun.getSource and others functions Commented Nov 18, 2015 at 17:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Callbacks were the way to go, cannot thank you enough for the reference links. I never really understood how they worked (and async for that matter) but these links provided thorough insight with easy to understand examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.