jquery在2函数结束时执行什么?
我有两个功能jquery在2函数结束时执行什么?,jquery,Jquery,我有两个功能 function f1() { } function f2() { } 我想在f1()和f2()完成后调用fend() 我正在寻找一种与“何时”或“承诺”功能相关的“干净”解决方案。以下是您可以做的事情: var state = 0; function f1() { //Do something state++; fend(); } function f2() { //Do something state++; fend(); }
function f1() {
}
function f2() {
}
我想在f1()和f2()完成后调用fend()
我正在寻找一种与“何时”或“承诺”功能相关的“干净”解决方案。以下是您可以做的事情:
var state = 0;
function f1() {
//Do something
state++;
fend();
}
function f2() {
//Do something
state++;
fend();
}
function fend() {
if (state == 2) {
console.log("fend called");
state = 0; //reset the state value
}
}
在每个函数结束时增加一个var,然后调用fend()。如果状态为2,则表示已执行2个函数
JSFIDLE:我认为您可以这样做:
var check = false;
function f1(){
if(check == true)
fend();
else
check = true;
}
function f2(){
if(check == true)
fend();
else
check = true;
}
当两个函数和第一个函数都完成时,检查为真。
第二次完成后,将调用fend
希望它能有所帮助这不仅限于jQuery,它只是JavaScript,但您每次都可以测试一个布尔值。在任一函数的末尾,布尔值将设置为true:
var didEitherFunctionFinish = false;
function f1() {
// f1()'s logic goes here
if(didEitherFunctionFinish) {
finalFunction();
}
didEitherFunctionFinish = true;
}
function f2() {
// f2()'s logic goes here
if(didEitherFunctionFinish) {
finalFunction();
}
didEitherFunctionFinish = true;
}
function finalFunction() {
// what happens after both f1() and f2() have been called
}
布尔值以false开头。在f1()或f2()的末尾,无论发生什么情况,它都被设置为true。在此之前,将运行一个测试,以查看其中一个函数是否已完成。如果有,则调用finalFunction()。是使用并解决它们。用于在解决两个延迟问题后触发回调
如果可能发生故障,还应处理故障等。如果您希望从
fend
函数中的f1
或f2
访问数据,也可以使用参数调用.resolve
。f1和f2函数中包含什么?取决于f1和f2是否执行异步操作。我的意思是,您可以只执行f1();f2();fend()代码>但我假设您想要异步执行它?
var f1 = function() {
var d = $.Deferred();
// A pretend async call
setTimeout(function() {
d.resolve();
}, 1000);
return d;
},
f2 = function() {
var d = $.Deferred();
d.resolve(); // This function resolves right away but f1 takes a second!
return d;
};
$.when(f1(), f2()).done(function() {
// This is your 'fend' function
alert('hi');
});