我需要在promise.then()中并行运行几个函数
我尝试使用类似波纹管的代码,但工作不正确:
function fadeElement(selector){
return function () {
return $(selector).fadeOut(400).promise();
}
}
function runParallel(owner, promises) {
return function () {
var differed = new $.Deferred();
var resolveDiffered = function () { differed.resolve(); };
$.when.apply(owner, promises).
then(resolveDiffered);
return differed.promise();
}
}
FormInput.prototype.ReloadPage = function(){
var firstOne = fadeElement('#element_Id_1');
var firstTwo = fadeElement('#element_Id_2');
var firstThree = fadeElement('#element_Id_3');
var secondOne = fadeElement('#element_Id_4');
var thirdOne = fadeElement('#element_Id_5');
var thirdTwo = fadeElement('#element_Id_6');
$.when(firstOne(), firstTwo(), firstThree())
.then(secondOne)
.then(
runParallel(this, [thirdOne(), thirdTwo()])
);
}
firstOne
,firstTwo
,firstThree
,secondOne
的运行时间没有400ms。thirdOne
,thirdTwo
-完全不运行。我认为我在
runParallel
中有一个错误,但是我所掌握的知识不足以理解何处。我认为是这样,因为此代码将起作用:$.when(firstOne(), firstTwo(), firstThree())
.then(secondOne)
.then(thirdOne)
.then(thirdTwo);
最佳答案
问题是,当您将这些函数传递给thirdOne
时,您正在调用thirdTwo
和runParallel
(从而开始了淡入过程):
.then(
runParallel(this, [thirdOne(), thirdTwo()])
);
相反,您应该删除最终的
()
并将函数传递给runParallel
,这会将每个方法映射到调用它的结果。更改调用每个承诺生成函数的时间的位置将使衰落过程延迟到其他承诺完成之后:function fadeElement(selector) {
return function() {
return $(selector).fadeOut(400).promise();
}
}
function runParallel(owner, promises) {
return function() {
return $.when.apply(owner, promises.map($.call, $.call))
}
}
FormInput.prototype.ReloadPage = function() {
var firstOne = fadeElement('#element_Id_1');
var firstTwo = fadeElement('#element_Id_2');
var firstThree = fadeElement('#element_Id_3');
var secondOne = fadeElement('#element_Id_4');
var thirdOne = fadeElement('#element_Id_5');
var thirdTwo = fadeElement('#element_Id_6');
$.when(firstOne(), firstTwo(), firstThree())
.then(secondOne)
.then(
runParallel(this, [thirdOne, thirdTwo])
);
}
function FormInput () {
}
new FormInput().ReloadPage()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element_Id_1">1</div>
<div id="element_Id_2">2</div>
<div id="element_Id_3">3</div>
<div id="element_Id_4">4</div>
<div id="element_Id_5">5</div>
<div id="element_Id_6">6</div>