0

I am writing an application in Javascript and JQuery and I need to follow a sequential order on functions calls, so I've thought in using a queue. I have seen this, but (if is possible) I would prefer abstract or avoid function(next) in my function calls like example below because I have a lot of custom functions:

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

Is it possible or there are another alternative and I don't know it?

3 Answers 3

0

None of this is tested, but... You could set up an array of functions and iterate through them:

var fn1 = function(){ code here };
var fn2 = function(){ code here };
var functionQueue = [ fn1, fn2 ];
$.each(function(functionQueue, functionItem){ functionItem(); });

or, if you specifically wanted to have a 'next()' function, you could do:

var fn1 = function(){ code here };
var fn2 = function(){ code here };
var functionIndex 0;
var functionQueue = [ fn1, fn2 ];
var next = function(){ functionQueue[functionIndex++]() }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, @K3N. I haven't worked out how to format code like that in SO [blush]
no problem! :) Everything isn't always obvious. Here is a link that can be useful for other things as well: stackoverflow.com/editing-help Just add four spaces in front, or, mark the block and hit ctrl+k
0

There must be various options.

One might use async and its waterfall function:

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
});

Comments

0

Since functions are first class objects, you can add them in an array and then use the Array.shift function to call them one by one (for a First-In-First-Out approach) :

//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())();
}

I hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.