Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript函数队列_Javascript_Function_Queue - Fatal编程技术网

Javascript函数队列

Javascript函数队列,javascript,function,queue,Javascript,Function,Queue,我正在用Javascript和JQuery编写一个应用程序,我需要遵循函数调用的顺序,所以我考虑使用队列。 我已经看到了,但是(如果可能的话)我更喜欢在我的函数调用中抽象或避免函数(下一步),如下面的示例所示,因为我有很多自定义函数: var fn1 = function(next){ console.log("I am FN1"); next(); }; 有没有可能,或者有其他选择,我不知道?这些都没有经过测试,但是。。。 您可以设置一个函数数组并对其进行迭代: var f

我正在用Javascript和JQuery编写一个应用程序,我需要遵循函数调用的顺序,所以我考虑使用队列。 我已经看到了,但是(如果可能的话)我更喜欢在我的函数调用中抽象或避免函数(下一步),如下面的示例所示,因为我有很多自定义函数:

var fn1 = function(next){
    console.log("I am FN1");
    next();
}; 

有没有可能,或者有其他选择,我不知道?

这些都没有经过测试,但是。。。 您可以设置一个函数数组并对其进行迭代:

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++]() }

必须有各种选择

人们可以使用它及其功能:


由于函数是第一类对象,您可以将它们添加到数组中,然后使用array.shift函数逐个调用它们(对于先进先出方法):


我希望这有帮助

谢谢,@K3N。我还没有弄清楚如何格式化这样的代码,所以[脸红]没问题!:)并非每件事都是显而易见的。这里有一个链接对其他事情也很有用:只需在前面添加四个空格,或者,标记块并按ctrl+k
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
});
//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())();
}