Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

jquery - Execute function queue in javascript

I'm trying to create a function queue with several functions in it. After the creation i want to execute each function in it's turn. But these function have delayed instructions inside of them, so i want to wait for each of the functions to complete its execution before the continuing.

My attempts:

var funqueue = [];
funqueue.push( function() {fun1() });
funqueue.push( function() {fun2() });
funqueue.push( function() {fun3() });
executeFunctionQueue(funqueue);

Where the execute function is:

function executeFunctionQueue(funqueue){
    var fun1=funqueue.pop;
    $.when(fun1()).then(executeFunctionQueue(funqueue));
}

But this does not work. How should i do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have functions that return Promises, this can be done very simply with a function like sequence:

// sequence :: [(undefined -> Promise<undefined>)] -> Promise<undefined>
function sequence(fns) {
    var fn = fns.shift();
    return fn ? fn().then(sequence.bind(null, fns)) : Promise.resolve(undefined);
}

sequence assumes that your asynchronous/Promise-returning functions do not take any inputs and do not produce any outputs (that they are merely being called for side-effects.)

An example usage of the sequence function is:

sequence([f1, f2, f3]);

function f1() {
    return new Promise(function (res) {
        setTimeout(function () {
            console.log('f1');
            res();
        }, 100);
    });
}

function f2() {
    return new Promise(function (res) {
        setTimeout(function () {
            console.log('f2');
            res();
        }, 1100);
    });
}

function f3() {
    return new Promise(function (res) {
        setTimeout(function () {
            console.log('f3');
            res();
        }, 10);
    });
}

This will log out 'f1', 'f2', and 'f3' in order with the varying, specified time delays in between.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...