我正在用Javascript和JQuery编写一个应用程序,我需要遵循函数调用的顺序,所以我想在使用队列。 我见过this,但是(如果可能的话)我更喜欢抽象或避免函数调用(下一个)在我的函数调用中如下例所示,因为我有很多自定义函数:
var fn1 = function(next){
console.log("I am FN1");
next();
};
是否可能或有另一种替代方案,我不知道呢?
答案 0 :(得分:0)
这些都没有经过测试,但...... 您可以设置一组函数并迭代它们:
var fn1 = function(){ code here };
var fn2 = function(){ code here };
var functionQueue = [ fn1, fn2 ];
$.each(function(functionQueue, functionItem){ functionItem(); });
或者,如果你特别想要'next()'函数,你可以这样做:
var fn1 = function(){ code here };
var fn2 = function(){ code here };
var functionIndex 0;
var functionQueue = [ fn1, fn2 ];
var next = function(){ functionQueue[functionIndex++]() }
答案 1 :(得分:0)
必须有各种选择。
async.waterfall([ function firstFunction(callback1) { callback1(null, 'one', 'two'); }, function thisIsCallback1(arg1, arg2, callback2) { // arg1 now equals 'one' and arg2 now equals 'two' callback2(null, 'three'); }, function thisIsCallback2(arg1, lastCallback) { // arg1 now equals 'three' lastCallback(null, 'done'); } ], function (err, result) { // result now equals 'done' // If the first argument of any function defin in the array // is not falsy, this, function will be invoked and // err will have its value });
答案 2 :(得分:0)
由于函数是第一类对象,您可以将它们添加到数组中,然后使用Array.shift函数逐个调用它们(对于先进先出方法):
//define your functions
function fn1(){...}
function fn2(){...}
//create an array to store your function into
var functionQueue = [];
//push the functions into the array
functionQueue.push(fn1);
functionQueue.push(fn2);
//loop through the array, each time calling the first function
while(functionQueue.length > 0){
(functionQueue.shift())();
}
我希望这有帮助!