javascript函数等到另一个函数完成
我有两个从android调用的javascript函数。 经过长时间的调试会议后,我意识到问题是由第二个函数在第一个函数完成之前被调用的事实引起的。 我已经使用延迟等搜索了这些示例,但它们都依赖于另一个中的函数调用。
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 }
如何强制getResult等待FuncInit? 有没有办法通过Javascript实现这一目标?
在我看来,延迟/承诺(正如你所提到的)是要走的路,而不是使用超时。
这是我刚刚编写的一个示例,用于演示如何使用延迟/承诺来完成它。
花一些时间玩延期。 一旦你真正理解它们,就可以很容易地执行异步任务。
希望这可以帮助!
$(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(); }
我有几种方法可以做到这一点。
使用回调:
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 }
使用超时(这可能是我的偏好):
var inited = false; function FunctInit(someVarible){ //init and fill screen inited = true; } function getResult(){ if (inited) { //return some variables } else { setTimeout(getResult, 250); } }
等待初始化发生:
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 }
以下答案可以帮助解决此类和其他类似情况,如同步AJAX调用 –
工作实例
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); } }); }