如何执行函数块

How to execute blocks of functions?

本文关键字:函数 执行 何执行      更新时间:2024-01-28

这是我的代码:

var testStacks = new Array();
function test(elem) {
    console.log(elem);
    ... asynch operations
}
testStacks.push(test("hello 0"));
testStacks.push(test("hello 1"));
testStacks.push(test("hello 2"));
testStacks.push(test("hello 3"));
testStacks.push(test("hello 4"));
// init first 3 functions
testStacks[0];
testStacks[1];
testStacks[2];

我想一次执行3个功能。因此hello 0hello 1hello 2在开始时一起开始。然后,一旦一个函数完成(它们执行异步操作),它就必须从数组中调用下一个函数(尚未执行)。等等…

似乎testStacks[0]什么都不做,当我推送函数时,它就会被执行。

我该怎么做?(我想避开setInterval())。

一个简单的方法可以是同时推送函数和参数。

var testStacks = new Array();
function test(elem) {
    console.log(elem);
    ... asynch operations
}
testStacks.push({func: test, param: "hello 0"});
testStacks.push({func: test, param: "hello 1"});
testStacks.push({func: test, param: "hello 2"});
testStacks.push({func: test, param: "hello 3"});
testStacks.push({func: test, param: "hello 4"});
// init first 3 functions
testStacks[0].func(testStacks[0].param);
testStacks[1].func(testStacks[1].param);
testStacks[2].func(testStacks[2].param);

当然,这可以用很多方法概括和清理,但应该给你一个基本的想法。

您正在执行函数并推送返回值。推送一个函数:

testStacks.push(function(){ test("hello 0"); });

无论选择什么解决方案,都需要第三方对象来管理当前调用堆栈,以及在操作完成时通知该对象的方法。关于以下(相当脏的)代码,我决定使用一个从test函数调用的简单回调:

var Stack = function (maxCalls, stack) {
    this.ongoing = 0;
    this.maxCalls = maxCalls;
    Array.prototype.push.apply(this, stack);
    this.next(); // starts immediately
};
Stack.prototype = Object.create(Array.prototype);
Stack.prototype.next = function () {
    var me = this;
    while (this.length && this.ongoing < this.maxCalls) {
        this.ongoing++;
        // calls the next function
        // passing a callback as a parameter
        this.shift()(function () {
            me.ongoing--;
            me.next();
        });
    }
};

有关使用案例,请参阅此演示:http://jsfiddle.net/wared/5eu8b/.正如您所看到的,函数是以先进先出的方式一个接一个地调用的,但它们以任何顺序完成。

希望它能有所帮助:)