JavaScript中的排序函数调用 - 回调是唯一的方法吗? [英] sequencing function calls in javascript - are callbacks the only way?
问题描述
我通过各种主题阅读,例如这一个。
I read through various threads like this one for example.
但它真的逃脱了我如何完成以下:
But it really escapes me how to accomplish the following:
我有4个功能,另一个顺序。注意他们是不正确的顺序,让我的观点。我想要的结果将输出1,2,3,4'
I have 4 functions, and want them happen one after another in sequence. Notice they are in incorrect order, to get my point across. I want the result that will output "1, 2, 3, 4'
function firstFunction(){
// some very time consuming asynchronous code...
console.log('1');
}
function thirdFunction(){
// definitely dont wanna do this until secondFunction is finished
console.log('3');
}
function secondFunction(){
// waits for firstFunction to be completed
console.log('2');
}
function fourthFunction(){
// last function, not executed until the other 3 are done.
console.log('4');
}
我试图找出回调,但我会迷路:(
I tried to figure out callbacks but am getting lost :(
不是有一些简单的方法吗?像循环一个数组...
Isn't there some simple way to do this? Like looping through an array...
推荐答案
这是一个开始使用 jQuery Deferred 的好机会。
It's a great chance to start using jQuery Deferred.
除了基于回调的解决方案,代码是可读,灵活和高度可维护的。
Apart from the callbacks-based solution the code is readable, flexible and highly maintainable
http://jsfiddle.net/zerkms/zJhph/
function firstFunction(){
var d = $.Deferred();
// some very time consuming asynchronous code...
setTimeout(function() {
console.log('1');
d.resolve();
}, 1000);
return d.promise();
}
function thirdFunction(){
var d = $.Deferred();
// definitely dont wanna do this until secondFunction is finished
setTimeout(function() {
console.log('3');
d.resolve();
}, 1000);
return d.promise();
}
function secondFunction(){
var d = $.Deferred();
setTimeout(function() {
console.log('2');
d.resolve();
}, 1000);
return d.promise();
}
function fourthFunction(){
var d = $.Deferred();
// last function, not executed until the other 3 are done.
setTimeout(function() {
console.log('4');
d.resolve();
}, 1000);
return d.promise();
}
firstFunction().pipe(secondFunction).pipe(thirdFunction).pipe(fourthFunction);
PS:作为异步代码的一个例子,我使用了 setTimeout
。主要的是,在异步部分的结尾,你需要调用 d.resolve()
来继续链接方法。
PS: as an example of asynchronous code I've used setTimeout
. The main thing is that in the end of the asynchronous part you need to call d.resolve()
to continue chaining methods.
进一步阅读: http://joseoncode.com/2011/ 09/26 / a-walkthrough-jquery-deferred-and-promise /
这篇关于JavaScript中的排序函数调用 - 回调是唯一的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!