0

I'm setting a flag called flag_done, which I use to make sure there were no errors when updating my database records line by line. If there are no errors, I will reset the database.

The updating works fine, the flag_done variable shows 2 different values with 2 consecutive identical alerts.

What am I missing?

var flag_done = "initial";
function updateDatabase(){
  UpdateList = JSON.parse(localStorage["UpdateList"]);  // get it from local
  if (UpdateList.length > 0 ){
    for (i = 0; i < UpdateList.length; i++) {
      set_url = "checks/"+UpdateList[i].id+".json";
      $.ajax({
        type: "PUT",
        url: set_url,
        data: JSON.stringify(UpdateList[i]),
        contentType: 'application/json', // format of request payload
        dataType: 'json', // format of the response
        success: function(msg) {
          // flag_done = "success";  // this actually worked but the same issue as error, the initial value shows up first when alerting twice!
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("OFFLINE!");
          flag_done = "error";  // This sets correctly
          alert("flag_done should be error: "+flag_done);  // Shows as error (correct)
        }
      } )
      alert("still inside for loop: "+flag_done);     // This shows initial and not error - ever!     
    }

    alert("flag_done: "+ flag_done); // shows initial
    alert("flag_done: "+ flag_done); // shows error!!

    if ( flag_done == "error" ) {
      alert("Couldn't SYNC right now, saved offline.");
    }else{
      alert("Updated OK");
      // resetDatabase();
    }
  } 
};
iamthing
  • 141
  • 2
  • 7
  • @WesFoster If that's true, that completely goes against everything I know about JS - in that it's inherently single threaded, and so the flag _can't_ be changed between the two `alert`s, as the outer function would need to run to completion before the ajax handlers can be run. If this is what's happening, I would be flagging it as a bug in whatever JS engine is running this. – James Thorpe Jul 28 '15 at 15:05
  • Short answer: `$.ajax()` is asynchronous. – emerson.marini Jul 28 '15 at 15:09
  • 1
    You really should learn about [`console.log()`](http://stackoverflow.com/questions/4539253/what-is-console-log) – D4V1D Jul 28 '15 at 15:37
  • I have accepted the answer from @Vanojx1, which is working. Thanks for all the input. I will investigate asynchronous ajax further as I found this sequence very unusual! – iamthing Jul 29 '15 at 03:14

1 Answers1

1

You need to manage this as an array of request

var theBigOne = [];

for (i = 0; i < UpdateList.length; i++) {
     var currentReq = $.ajax({........});
     theBigOne.push(currentReq);
}

$.when.apply($, theBigOne).then(function(results) {
     console.log(results);
}, 
function(e) {
     console.log("Something failed");
});

your spam of alert don't make you see the real ajax execution process in this case ( thats asynchronous ).... its a sort of syncro camouflage

Vanojx1
  • 5,574
  • 2
  • 23
  • 37
  • thanks for the solution. If I set the flag inside the function(e), I had the same issue, so I moved the resetDatabase() call just under console.log(results); and it works. Now it resets the database when online (and fully updated) and doesn't attempt to when offline! – iamthing Jul 29 '15 at 03:08
  • you don't need to set the flag anymore... just reset the db in the first function or use the alert alert("Couldn't SYNC right now, saved offline."); in the second one. this function its a sort of if statement, ajax done or ajax failed. – Vanojx1 Jul 29 '15 at 07:22