0

Its an ASP.Net application, and this is part of a javascript function:

//x & y are global variables
x = document.getElementById(MapXVal).value;
y = document.getElementById(MapYVal).value;
if ((x === undefined || x === null || x === "") &&
    (XVal !== undefined && XVal !== null && XVal !== "")) {

        x = document.getElementById(XVal).value;
        y = document.getElementById(YVal).value;
        point = new esri.geometry.Point(x, y, new esri.SpatialReference({ "wkt": ...}));
        var OutSR = new esri.SpatialReference({ "wkid": 102113 });
        gsvc.project([point], OutSR, function (projectedPoints) {

            var output = projectedPoints[0];
            alert('deep inside');
            x = output.x;
            y = output.y;
        });
    }
alert('outer scope');
if (x !== null && y !== null && x !== "" && y !== "") {
    //do something with x & y
}

What I am trying to do: call the function gsvc.project...etc to calcuate the values for my global variables x & y which will be used later on in the code.

Problem: the code within gsvc.project will be executed after its containing function is done executing (e.g. the message outer scope will be shown before deep inside) so I will not have the values for x & y until its too late.

I am not an expert in Javascript, so I've been looking for why this is happening and found nothing much up to this point. I already solved the problem by duplicating my code inside the gsvc.project..function(projectedPoints){ declaration, but I dont want to have duplicates and would like to know if there is a solution to my problem: control the execution, cause a delay, or maybe a better way to do this?

Jafar Kofahi
  • 763
  • 6
  • 22
  • 2
    Resume your program flow from the `gsvc.project` callback, that's how you deal with asynchronous stuff. – bfavaretto Aug 06 '13 at 18:55
  • 1
    @Vineet1982: No, absolutely not. – Bergi Aug 06 '13 at 18:57
  • @bfavaretto I cant do that from within the `gsvc.project` callback func. Because this function might not be called all the time. Is this the only way? – Jafar Kofahi Aug 06 '13 at 19:02
  • You mean because of the if? In this case, duplicate code. – bfavaretto Aug 06 '13 at 19:10
  • so **it is** the only way.. ok I will restructure my code..thnx – Jafar Kofahi Aug 06 '13 at 19:15
  • @JafarKofahi, you could also look at a promise system like https://github.com/kriskowal/q (frameworks often include promises also) for a different way. But either way you are factoring the dependent code out of the function setting up the callback.. – lossleader Aug 06 '13 at 20:14

0 Answers0