简体   繁体   中英

Wait unitl ajax and its callback function finish

I am building a web app that allows users to perform a number of actions simultaneously. For example, user can open a list, delete a list, or add a new list.

Each action makes an ajax call and executes a callback function to update UI upon success. I want to make sure these actions are performed in a serialized manner, so that the UI does not go out of sync. For example, if user opens a list, but deletes the list a fraction of a second later, depending on which ajax call finsihes first, it may display the list which is supposed to be now deleted.

To accomplish this, for each action, I want to wait until an ajax call and its callback function are finished. How can I achieve this?

With Jquery, you could add async: false to your Ajax call or use Jquery deferred to make sure an action is only issued after the Ajax calls are finished (assuming you use Jquery).

If you have multiple Ajax requests, an example could look like:

$.ajax({url: url}).pipe(function() {
  // some ajax stuff
  return $.ajax({});
}).pipe(function() {
  // some more ajax stuff (3rd request)
  return $.ajax({});
}).done(function() {
  // done with all ajax requests...
});

If you're using jQuery the .always() callback is called after .done() / .fail() .

$.ajax("example.php")
    .done(function() {
        alert("success");
    })
    .fail(function() {
        alert("error");
    })
    .always(function() {
        alert("complete"); //Called after done/fail callbacks
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM