0
votes

I know it is asynchronicity, but I have followed the steps of adding callback function Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference but I can only access the changes inside the callback function. Here is my code snippet. Please help

function callback(point) {

       for (i = 0; i < point.length; i++) {
           myDate[i] = point[i].date_time;
           myValue[i] = point[i].my_value;
       }

       for (j = 0; j < myDate.length; j++) {
           var temp = new Array(myDate[j], myValue[j]);
           mySeries[j] = temp;
       }
       alert("MYSERIES in scope:  " + mySeries); //defined

   }
   alert("MYSERIES out scope:  " + mySeries); // undefined
   getAllMessagesforChart(callback);

   function getAllMessagesforChart(callback) {
                var data = @Html.Raw(JsonConvert.SerializeObject(this.Model))


        $.ajax({
            url: '/messages/GetMessagesforChat',
            data: {
                id: data.id,
            },
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'JSON'

        }).success(function (data) {
            callback(data);
        }).error(function (e) {
            alert("error " + e)
        })     

   }
2
it's because it's not "after".Alnitak
Are you curious about why your mySeries variable is undefined outside of callback function?hina10531
Yes I am a newbie and I need help in thatuser2217303
Well you kind of answered it yourself, it's out of scope. You defined it inside callback. If you add var mySeries; outside the function, then the scope would be global and you could see it.dmeglio

2 Answers

1
votes

I hope this helps clear things up for you--

It is not an issue of scope. It is a matter of the order the statements are executed. If you order something from amazon.com, do you immediately go to your front stoop and expect to find the package? No, you have to wait for the drone to get there.

The mySeries variable is a global variable. It is not "out of scope" outside the callback() function. And it's not that you can't access the changes outside the callback() function; it's that you can't access the changes before they have been made. The alert with "MYSERIES out scope" appears in the code after the callback() function is defined, but it is executed before the callback() function is executed.

Even if you were to change the order of the following two statements, the alert would still be executed before the callback function, because the callback function is not executed until the ajax call returns, assynchronously.

getAllMessagesforChart(callback);
alert("MYSERIES out scope:  " + mySeries); // undefined
0
votes

Define mySeries outside the callback function:

var mySeries = [];
function callback(point) { ... }

JavaScript created mySeries when you first put data into it. So it gets globally defined after you invoke the callback.