tl;dr
What is the best way to wait for a $.getJSON to complete before executing the rest of the code if it's not just one function but many that rely on the the response?
Longer explanation:
I have a javascript application that has reached a certain level of complexity. Closing in on a thousand lines of code and two dozen function and no end in sight. The application relies on values stored in a database. More precisely, I don't have a single function that is relying on the requested data but most of my functions use those values and some point.
So far, I pulled the data from the db in php and just echoed them into input fields and then read those in js. But with an increasing number of variables transferred this way, this is getting unwieldy and does not seem very elegant. I do have most data available in objects and stuffing their member variables in input fields seems ... clunky.
I pondered different ways of data transfer and settled on jquery ajax for several reasons, not the least being a clean separation of layers and me using jquery ajax already for other things.
The problem: I ran into race condition problems. Some of my code - that relies on the data requested by getJSON - is executed before the request is finished. And that breaks the whole application. I already researched a bit and know now that there are several ways to solve this, however I'm not experienced to judge which approach I should chose.
async: false
, this still works and is likely the easiest thing to implement, but it is marked as deprecated and as such I'm hesitant to use it. $.getJSON("../sender.php", params, function (result) {
//my whole application
});
$.when( req1, req2, req3 ).done( ... )
around every function I use a requested value in. This doesn't seem good for readabilty and I've learned that clean, readable code is usually the better code than complex constructions. var request = new XMLHttpRequest();
request.open('GET', '../sender.php', false);
request.send(params);
if (request.status === 200) {
//fill the variables with the returned values
}
As ajax is asynchronous request ajax method will not wait for other method to execute Best practice to call dependant methods will be in success of ajax call It will execute/ call function only after ajax response recieved. You can make request by various ways
I will suggest you to go with 1 as asynchronous request can be served as synchronous by async: "false"