
let LoadingTasks = (() => {
    let activeTask = null;
    let tasks = [];
    let runNextTask;

    runNextTask = function() {
        if (activeTask || tasks.length === 0)
            return;
        activeTask = (tasks.shift());
        let taskResult = null;
        try {
            taskResult = activeTask.fnc();
        }
        catch (err) {
            taskResult = Promise.reject(err);
        }
        if (!(taskResult instanceof Promise))
            taskResult = Promise.resolve(activeTask);
        taskResult
            .then(() => {
                let ok = activeTask.ok;
                activeTask = null;
                ok(taskResult.result);
            })
            .catch(() => {
                let ko = activeTask.ko;
                activeTask = null;
                ko(taskResult.result);
            })
            .finally(() => {
                runNextTask();
            });
    };

    return {
        push: async function(task) {
            return new Promise((ok, ko) => {
                tasks.push({ fnc: task, ok: ok, ko: ko });
                runNextTask();
            });
        }
    };
})();

