从JavaScript数组执行多个回调

Execute multiple callbacks from a JavaScript array

本文关键字:回调 执行 JavaScript 数组      更新时间:2023-09-26

我有一个回调数组,这样每个回调都接受另一个回调,当作业完成时执行。例子:

var queue = [
    function (done) {
        console.log('Executing first job');
        setTimeout(done, 1000); // actually an AJAX call here
            // I can't call abort() for the request
    },
    function (done) {
        console.log('Executing second job');
        setTimeout(done, 1000);
            // also AJAX call here
            // it is made from a third-party library that I can't change
            // this means that I can't call abort() on it
    },
    function (done) {
        console.log('Executing third job');
        setTimeout(done, 1000);
    },
    function (done) {
        console.log('Executing fourth job');
        setTimeout(done, 1000);
    } // and so forth
];
var proceed = true;
(function dequeue() {
    var fn = queue.shift();
    proceed && fn instanceof Function && fn(dequeue);
})();

这对我来说很好,除了加快一切,我最好一次启动四个回调,同时仍然能够通过从其他地方更改proceed标志来停止进一步执行。我怎么做呢?

我在这个项目中使用了最新版本的jQuery,所以如果库中有任何东西可以帮助我完成这个任务,我会使用它。

http://jsfiddle.net/2Jg6r/

var queue = [];
// let's think we have a thousand of jobs
for (var i = 0; i < 1000; i++) {
    (function(jobNumber) {
        queue.push(function (done) {
            console.log('Started job '+ jobNumber);
            setTimeout(function() {
                console.log('Finished job '+ jobNumber);    
                done();
            }, 1000);
        });
    })(i);
}
var proceed = true;
setTimeout(function() {
    console.log('Full stop called after 10 seconds');
    proceed = false;
}, 10000);
queue.depth = 0;
queue.maxDepth = 4;
(function dequeue() {
    while (queue.depth < queue.maxDepth) {
        queue.depth += 1;
        var fn = queue.shift();
        proceed && fn instanceof Function && fn(function() {
            queue.depth -= 1;
            dequeue();
        });
    }
})();