How to write a simple queue function like promises

Step 1: Starting point (asynchronous)

Here is a simulation of four tasks. Each task has a own function, and needs a different execution time.
With press on the "start" button the functions are called and the animation shows the progress.
You will notice that each task is terminated in a different order, but this is not the order in which the task was called.

Order of finished functions:

Order of calling the animations:

$("#start-asynchronous")
    .on("click", function () {
        oneAsync();
        twoAsync();
        threeAsync();
        fourAsync();
    });

The Problem (in some cases):

Target:

In the next step i show a example to handle the problem with a callback hell or called also pyramid of hell.

Step 2: Callback Hell

Order of finished functions:

Order of calling the animations:

Here you can very well recognize the pyramid,
which can be very confusing and is therefore called the Pyramid of Hell.
But the order is exactly the wanted.

$("#start-callbackHell")
    .on("click", function () {
        oneHell(function () {
            twoHell(function () {
                threeHell(function () {
                    fourHell()
                })
            })
        });
    });

Example of the first function with callback

function oneHell(fnCallback) {
    // ...some calculations...

    if ($.isFunction(fnCallback)) {
        fnCallback();
    }
}

The Problem:

The code is not easy to read and results in difficulties in understanding complex applications

Target:

In the next step i show a example to handle the problem with a small written queue function.

Step 3: Build a queue

Order of finished functions:

The queue function and order of calling functions:

function runQueue(queue) {
    if (!queue.length) {
        return;
    }
    var arr = queue[0];
    arr(function () {
        runQueue(queue.slice(1));
    });
}

$("#start-queue")
    .on("click", function () {
        runQueue([
            function(c){oneQ(c);},
            function(c){twoQ(c);},
            function(c){threeQ(c);},
            function(){fourQ();}
        ]);
    });

Result

My written runQueue function is a small recursive function, all functions are given in an array structure.
The function calls on until no more functions are in the array.
But the result is like step 2 with a similar structure like step 1 for easy reading.
You can download the js code of the page here: main.js

Future

In the Future the modern browsers support the new promises https://www.promisejs.org/.
Its in an very similar structure like my queue function but for old browsers my function could be helpful.
But there are another great plugins with advanced settings an possibility's like: https://github.com/kriskowal/q

Contact

Dandy Umlauft from Bielastraße 9, 04178 Leipzig
dandy.umlauft@googlemail.com