0

I have declared two functions and one global variable . i am setting the global variable value in first method and trying to access the value in second method .

var Result=[];

setResult();
getResult(); 

function setResult(){
    var resultJson=[];
    resultJson.push({ "param1":"test","result":"success" });
    Result=resultJson;
}

function getResult(){
    console.log(Result);
}

sometimes i am getting the proper value in console as object=[{ "param1":"test","result":"success" }]

sometimes i am getting only empty array: [] how can i resolve this problem.

user3718420
  • 151
  • 1
  • 3
  • 14
  • 3
    I would expect the code shown to *always* work. Have you simplified it in order to post here, perhaps removing a call to an asynchronous function? (Also, just as an aside, there is no JSON in the code shown, so the variable called `resultJson` should probably be called something else.) – nnnnnn Jul 10 '16 at 08:07
  • Yes i have simplified the code for posting it here . the json values are getting populated from the response values getting after making an ajax call. the whole code is loading inside an angular js controller. resultJson is not getting used anywhere else also. – user3718420 Jul 10 '16 at 08:18
  • it is something related to time which i am not able to identity. – user3718420 Jul 10 '16 at 08:19
  • OK, with that additional information about your real code (which really should've been mentioned in the question rather than a comment) I've closed this as a duplicate. There's some good information in the answers to that other question. The short answer is you have to restructure your code a little when dealing with Ajax (or other asynchronous) functions - at the moment you're trying to use the result before the Ajax response is received. – nnnnnn Jul 10 '16 at 08:26

0 Answers0