javascript函数等待另一个函数完成 [英] javascript function wait until another function to finish
问题描述
我有两个从android调用的javascript函数。经过漫长的调试会话,我终于意识到,问题是由于第二个函数在第一个函数完成之前被调用的事实引起的。我已经搜索的例子与deferred等,但他们都依赖于另一个函数调用。
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
}
如何强制getResult等待FuncInit?有没有办法通过Javascript实现?
How can I force getResult to wait FuncInit? Is there a way to achieve this via Javascript?
推荐答案
在我看来,延迟/承诺
这里是一个 example 我刚刚写了一篇文章来演示如何使用deferred / promise来做到这一点。
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.
希望这有助于!
$(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();
}
这篇关于javascript函数等待另一个函数完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!