How to ensure that AJAX requests called in a specific order receive a response in the same order?

How to ensure that AJAX requests called in a specific order receive a response in the same order?

+5
source share
2 answers

First, keep in mind that the server itself cannot return responses in the order in which requests were received. Imagine first you run a complex ajax request and a simple one for a second (possibly referring to some cached static data). The second query is likely to return before the complex one returns. You can see how this complicates the situation; If the order for which the requests are received does not coincide with the order of responses returned, how can assurances be made?

You have several options:

1) You can synchronize requests instead of asynchronous. However, this will block the browser.

2). A better approach would be to combine the queries in such a way that the next query is only launched after the first is completed, by running the second query after the first return.

As a side note, if you find that you have two ajax operations that you need for the chain, it might make sense to create a server endpoint to handle two operations in a single request. those. just make ajax request to do whatever you need.

+5
source

Another option is to have a counter in your Javascript code that increments each time this AJAX call is made. Then pass that value in your AJAX call and include that value in your response. This way you can keep track of the order in which the answers should be.

+1
source

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


All Articles