Я обычно структурирую свои скрипты в javascript, например, или что-то похожее, когда скрипт зависит от какого-то ajax или ответа сервера в целом. Я действительно не чувствую, что это самый эффективный способ сделать что-то, так что было бы лучшим способом сделать эти типы сценариев?
function someclass() {
//some internal variables here
this.var1 = null;
this.var2 = null;
...
//some ajax function which gets some critical information for the other functions
this.getAJAX = function() {
self = this;
urls = "someurlhere";
//jquery ajax function
$.ajax({
type: "GET",
url: url,
dataType: 'json',
complete: function (xhr, textStatus) {
//get the response from the server
data = JSON.parse(xhr.responseText);
//call the function which will process the information
self.processAJAX(data);
}
})
this.processAJAX = function(data) {
//set some of the internal variables here
//according to the response from the server
//now that the internal variables are set,
//I can call some other functions which will
//use the data somehow
this.doSomething();
}
this.doSomething = function() {
//do something here
}
}
Так что я бы использовал скрипт примерно так:
//instantiate the class
foo = new someClass();
//get the information from the server
//and the processAjax function will eventually
//call the doSomething function
foo.getAjax();
Так что мне действительно не нравится это, потому что при использовании сценария не ясно, что происходит. Я хотел бы иметь возможность сделать что-то вроде этого:
//instantiate the class
foo = new someClass();
//get info from the server
//in this example, the processAJAX function will not call the doSomething
foo.getAjax();
//do something
foo.doSomething();
Это, однако, не работает, потому что обычно ответ от сервера занимает некоторое время, поэтому, когда вызывается doSomething, необходимой информации еще нет, поэтому функция не делает то, что должна делать.
Как заставить это работать?
Я уверен, что ответ уже находится где-то в StackOverflow, однако я не смог ничего найти, поэтому я был бы признателен за то и другое: либо за ответ, либо за ссылку на ресурс, который мог бы объяснить это, что возможно в StackOverflow. Любая помощь приветствуется. Спасибо.