A similar question has been asked many other times, I'm aware, but my case is rather specific and has, to my knowledge, never been touched on before. At least from what I can find.
What I'm doing is building objects using a UID. Everything that the object is built with requires this UID and it requires it to be verified as unique before anything can be done with it.
I'm randomly generating the UID in javascript and I'm checking it against all other entries in a SQL database. I'm posting to the database using PHP and Ajax.
The core issue I'm having is that Javascript doesn't wait for the Ajax response and instead just keeps rolling. Ajax has to use a success handler. This is strictly not possible for me to use because I cannot do anything until I know for certain that the UID is verified.
Are there any workarounds or solutions to this? Promises won't work because, as I stated before, the UID is integral in building the object in and of itself, so using placeholders won't work.
Thanks in advance!
You can just send a synchronous Ajax request, like that:
var response = $.ajax({ url : "http://api.jquery.com/jquery.ajax/", async : false });
(though that is not a very good practice)
Ok. One possible solution, if your UID is generated on the server randomly, you may supply it directly to your index.html with the script tag.
<head>
<script src="path_to_url_that_provides_generated_script"></script>
<script .... other scripts></script>
</head>
And this generated script would be something like:
var UID = "xxxx-xxxx-xxxx-xxxx";
That way you don't even need to do an ajax request, since your uid will known before any other script is processed.
The best method, I have discovered, was to rewrite my code to not begin object creation until I had the UID in the first place. While this does take up a considerable amount of time to complete and ensure that no unwieldy bugs are present, there's no other real solution that's both simple and effective.
As it turns out, foresight is something that always seems to keep good programmers from writing and rewriting their work again.
Special thanks to @Vladimir M for the solution.