V
V
Vladimir Storozhuk2017-02-27 16:28:59
JavaScript
Vladimir Storozhuk, 2017-02-27 16:28:59

How to synchronize code with asynchronous ajax call?

I had this problem: I send a post request to a php script to generate a level map (json). It comes, but by the time it is processed, all the written code has already worked. And as a result, all the necessary values ​​on the map (a two-dimensional array with instances of the "one cell" class) were zero. This array is created with these zero-value instances, and sent for generation.
Initializations of different sublevels of the "engine" are called from the global scope. The first Init creates an environment along with a map, then the sublevels that need this map are initialized.
Console output about map readiness appears only at the end of the execution of the global scope. Does anyone have any idea? I have already tried all the crutches.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2017-02-27
@WaldeMar1321

Either make the call synchronous (JS execution will completely stop before the response is received), or move the code that needs the map into a callback or promise and execute it after the map is received.

V
Vitaly, 2017-02-27
@vshvydky

Vladimir, the surest and most reliable way is to learn javascript. spend 2 days reading learn.javascript.ru and you will have no such questions. If you don't do this, you'll never understand why or how from the answers here. The only thing you will see is the key, how to make Ajax synchronous and you will make shit codes ....
Therefore, I recommend an easy way, quickly familiarize yourself with the documentation on the language. Otherwise, the level of your questions will not rise even after half a year ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question