Javascript Asynchronous Function

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

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

In the second function ( saveData()), I also execute an asyn request to the server to write some data. In the callback of this request, I call loadData()to update the data.

Now the problem: in the function, saveData()I want to wait for it to finish loadData()before I show the dialog (for example, alert('Data saved'))

I assume this is a common problem, but I could not find a solution for it (if there is one ...)

The solution will be to make the requests synchronous, but the infrastructure used does not offer this, and I hope that there will be a better solution.

Thanks everyone!

+3
source share
2 answers

The trick in these situations is to nest “successful” callbacks as follows:

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

If your function loadData()looks something like this:

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

... then you can give it a callback argument that is called immediately 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 can implement your function saveData()as follows:

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 can still call the function loadData()without any arguments in other parts of your script.

+10
source

- , , . jquery, .

+1

Source: https://habr.com/ru/post/1749375/


All Articles