我正在尝试弄清楚如何等到所有指定的函数完成后再调用不同的函数。现在我有一些类似的东西:
for (i = 0; i < valueArray.length; i++){
SwitchCall(valueArray[i]);
}
function SwitchCall(value){
switch(value){
case 1: FunctionOne(); break;
case 2: FunctionTwo(); break;
case 3: FunctionThree(); break;
}
}
SomeOtherFunction()
其中 valueArray
是包含 {1,2,3} 的某个子集的数组。我需要在调用 SomeOtherFunction
之前完成数组中指定的所有函数。我想我需要在这三个函数中添加某种回调,但我无法在这些回调中调用 SomeOtherFunction
因为我可能需要先完成其他函数。我如何等待所有这些功能完成后再继续?
最佳答案
您可以将 Promise 与 jQuery Deferred 一起使用
var async1 = FunctionOne();
var async2 = FunctionTwo();
var async3 = FunctionThree();
$.when(async1, async2, async3).done(function(async1, async2, async3) {
//When all done!
SomeOtherFunction()
});
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
关于javascript - 交换机内的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110961/