jQuery - 按顺序运行多个方法 [英] jQuery - run multiple methods sequentially
问题描述
如果我这样做:
method();
method();
两个电话将同时并行(同时)
both calls will run in parallel (at same time)
我只想制作第二种方法();等到第一个方法();在开始之前完成,并且动态地做,因为我不知道我将启动method()多少次;同时。
i just would like to make the second method(); wait until the first method(); is finished before to start, and do it dynamically cause i can't know how many times i will launch method(); at same time .
有可能吗?
例如,那些同时运行我可以见... http://jsfiddle.net/Lcgb8/
just for example, those runs at same time as i can see... http://jsfiddle.net/Lcgb8/
推荐答案
例如
function method() {
var d = $.Deferred();
//do something async
setTimeout(function () {
d.resolve('some data'); //inform listeners that the process is completed
}, 2000);
return d; //return the deferred object
}
然后你可以这样做:
method().then(method).then(method).then(method);
请注意,每个调用的返回值将分别作为第一个参数传递给下一个调用。
Note that the return value of each call will be passed as first argument to the next call, respectively.
编辑:这是一个关于如何动态排队异步操作的示例。
Here's an example on how you could queue the async operations dynamically.
function changeColorAsync(color) {
var d = $.Deferred();
setTimeout(function () {
$('body').css('background', color);
d.resolve();
}, 4000);
return d;
}
$(function () {
$('#color-form').on('submit', function (e) {
var color = $(this).find(':checked').val(), d;
d = d?
d.then(changeColorAsync.bind(this, color)) :
changeColorAsync(color);
return false;
});
});
这篇关于jQuery - 按顺序运行多个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!