0

I'm facing a problem where for some reason the flow of my app is asynchronous and doesn't go according to expectations. Maybe I'm misunderstanding Ajax, could someone advise me how to structure my flow properly:

I have a document.onReady() block of code where I define what happens on startup. On startup I need to load a bunch of data from the DB, which is an Ajax call to the server.

$(document).ready(function() {

   // ... some GUI startup steps go here ...

   // Now, I also need to pre-load a DB fetch in my app
   var activities = ajaxGetActivities();
   // ... Do something with 'activities' here
   parseActivities(activities);
}

AJAX method ajaxGetActivities() (no issues here, it returns the right thing)

   function ajaxGetActivities() {   

        $.ajax({
            type : "post",
            dataType : "json",
            url : '/myapp/activityFetch.mvc',  
            data : '', // no data
            success : function(data) {
                var result = otherAjaxProcessing(data); // this is OK, it works
                return result;  // returns the right result, OK
            },
            error : function(data) {
                alert('System Error, data: ' + data);
                return null;
            }
        });   
    }

What's happening is the debugger immediately drops to the next line in Snippet #1, parseActivities(), but at that time the variable activities is NULL. I assume the Ajax call hasn't started or completed yet. At some point later on, I hit my breakpoint inside the Ajax call, but it's sort of useless now because the flow has already gone on to the next steps in document.onReady where my activities variable is NULL!

Somehow I'm not synchronizing the result of the DB Fetch with the next steps in document.onReady that require it. I verified that I'm returning the right thing from the Ajax method, but document.onReady never picks it up.

gene b.
  • 10,512
  • 21
  • 115
  • 227
  • 1
    Your function doesn't return ANYTHING. A return in a callback does not return to the outer function. Beyond that ajax is **asynchronous** – charlietfl Nov 24 '17 at 23:10
  • thanks I fixed it based on your tip. Now document.onReady just calls the Ajax method, and the callback is a separate function that proceeds with the rest of what's required. – gene b. Nov 24 '17 at 23:25
  • Using promises would be better than using callbacks: `$.ajax(url,config).then(...` – HMR Nov 25 '17 at 06:04

0 Answers0