J
J
Jesse Pinkman2021-06-26 11:48:53
AJAX
Jesse Pinkman, 2021-06-26 11:48:53

async: false - bad practice?

Hey!
There was a need for synchronous ajax requests.
By adding this option, everything starts working as it should, but the thought that this is bad practice and the like does not give me rest. There is no specific example, it will be difficult to write all the code within this site, but here's what I can say: SPA application, mutation observer catches changes, checks and fills the array, then makes a request. But here, for some reason, ajax does not wait until the array is filled and immediately executes the request.

Are there cases where the use of synchronous requests is justified, as in my case, or does this mean that the logic is lame and it is best to rewrite everything so that there would be no need for synchronism?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-06-26
@jessepinkman010101

In the browser, both your JS and the user interface and much more are executed in one thread. And if you block this thread with long calculations or something else, then all this will stop. For the user, the tab will freeze. Neither links nor buttons will work, even closing it in the usual ways will be problematic.
A synchronous request blocks the thread for the entire time the request is sent and the response is received, moreover, just like that, in turn, because it won’t work here again. Add to this the fact that the network is usually a slow thing.

The mutation observer catches the changes, checks and populates the array, and then makes the request. But here, for some reason, ajax does not wait until the array is filled and immediately executes the request.
In addition, a synchronous request will not solve this problem, on the contrary, it will exacerbate it, since MutationObserver will also not be able to work out until the request is completed.
Are there any cases where synchronous requests are justified?
the only reasonable use is sending data before closing a tab on dinosaurs without sendBeacon
support. Note that in the modern fetch api there is not even such a possibility as sending a synchronous request, and for good reason.
the logic is lame and it's best to rewrite everything
unfortunately, the appearance of asynchrony in one place can lead to the appearance of asynchrony in many other places, no other way. So yes, it will have to be rewritten. But this is inevitable, since many apis in a modern browser (the same MutationObserver) only work asynchronously. Fortunately, there are promises and async/await sugar over them, which greatly simplifies this task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question