I have two javascript functions that are called from android. After long debug sessions finally I realized that the problem is arising from the fact that second function is getting called before first one is finished. I already searched the examples with deferred etc, but they all depends on function calls within another one.
function FunctInit(someVarible){ //someVariable is sent from android, cannot call again from getResult
//init and fill screen
}
function getResult(){ //also getResult need to be called from android via button
//return some variables
}
How can I force getResult to wait FuncInit? Is there a way to achieve this via Javascript?
This question is related to
javascript
jquery
callback
jquery-deferred
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
There are several ways I can think of to do this.
Use a callback:
function FunctInit(someVarible){
//init and fill screen
AndroidCallGetResult(); // Enables Android button.
}
function getResult(){ // Called from Android button only after button is enabled
//return some variables
}
Use a Timeout (this would probably be my preference):
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
if (inited) {
//return some variables
} else {
setTimeout(getResult, 250);
}
}
Wait for the initialization to occur:
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
var a = 1;
do { a=1; }
while(!inited);
//return some variables
}
Source: Stackoverflow.com