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?
In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.
Here is an example I have just written to demonstrate how you could do it using deferreds/promises.
Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.
Hope this helps!
$(function(){
function1().done(function(){
// function1 is done, we can now call function2
console.log('function1 is done!');
function2().done(function(){
//function2 is done
console.log('function2 is done!');
});
});
});
function function1(){
var dfrd1 = $.Deferred();
var dfrd2= $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function1 is done!');
dfrd1.resolve();
}, 1000);
setTimeout(function(){
// doing more async stuff
console.log('task 2 in function1 is done!');
dfrd2.resolve();
}, 750);
return $.when(dfrd1, dfrd2).done(function(){
console.log('both tasks in function1 are done');
// Both asyncs tasks are done
}).promise();
}
function function2(){
var dfrd1 = $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function2 is done!');
dfrd1.resolve();
}, 2000);
return dfrd1.promise();
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With