Ben
Ben

Reputation: 245

Javascript asynchronous function

I have a problem understanding how this could/should be solved.

I have two functions. In the first function ( I call it loadData() ) I'm doing an asynchronous request to the server to load some data.

In the second function ( saveData() ) I'm also doing an asyn request to the server to write some data. In the callback of this request I'm calling loadData() to refresh the data.

Now the problem: In the saveData() function I want to wait for loadData() to be finished before I show a dialog (like alert('Data saved'))

I guess this is a common problem, but I couldn't find the solution for it (if there is one..)

A solution would be to make the requests synchronous, but the framework I'm using doesn't offer that and I hope there's a better solution..

Thanks to all!

Upvotes: 3

Views: 5176

Answers (2)

Jorge Rivera
Jorge Rivera

Reputation: 775

Nesting functions is a solution but is a bad idea when it comes to code quality. You may want to take a look to jquery deferred object to solve it.

Deferred documentation

Upvotes: 1

Daniel Vassallo
Daniel Vassallo

Reputation: 344581

The trick in these situations is to nest the "success" callbacks like this:

$.ajax({ 
   url: "/loadData", 
   success: function () {
      // Data Loaded... Save the data
      $.ajax({ 
         url: "/saveData", 
         success: function () {
            // Data Saved... Display alert
            alert('Data saved');
         }
      });
   }
});

If your loadData() function looks something like this:

function loadData() {
   .ajax({ 
      url: "/loadData", 
      success: function () {
         // Data Loaded... Process the data
      }
   });
}

... then you may want to give it a callback argument that gets invoked just before the success callback returns:

function loadData(myCallback) {
   .ajax({ 
      url: "/loadData", 
      success: function () {
         // Data Loaded... Process the data

         // ... Your Data Processing Logic ...

         // Invoke the callback (if one was passed):
         if (typeof myCallback === 'function') {
            myCallback();
         }
      }
   });
}

Then you would be able to implement your saveData() function like this:

function saveData() {
   loadData(function () {
       // Data Loaded (and processed by loadData())... Save the data
      .ajax({ 
         url: "/saveData", 
         success: function () {
            // Data Saved... Display alert
            alert('Data saved');
         }
      });
   });
}

You would still be able to call the loadData() function without any arguments in other parts of your script.

Upvotes: 10

Related Questions