Jquery use queue to implement Ajax request queue Simple Example

Packaging method

var axmq = {
    //Queues
    queues: [],
    //network request
    request: null,
    //Execution queue
    render: function() {
        $(document).queue(axmq.queues);
    },
    //append queue
    append: function(func) {
        axmq.queues.push(func);
    },
    //clear queue
    clear: function() {
        $(document).dequeue();
        if (0 === $(document).queue().length) {
            axmq.queues = [];
            $(document).clearQueue();
        }
    },
    //POST request
    post: function(args) {
        var params = {
            url: 'https://www.sample.com/api',
            headers: {},
            data: {},
            buffer: function() {},
            callback: function() {}
        };
        $.extend(params, args);
        var headers = {
            Accept: 'application/json;charset=utf-8'
        };
        if (Object.keys(params.headers).length > 0) {
            $.extend(headers, params.headers);
        }
        if (axmq.request == null) {
            axmq.request = $.ajax({
                async: true,
                type: 'POST',
                url: params.url,
                headers: headers,
                data: params.data,
                dataType: 'JSON',
                beforeSend: function() {
                    params.buffer();
                },
                success: function(res) {
                    console.log(res);
                    axmq.request = null;
                    axmq.clear();
                    params.callback(res);
                },
                error: function(err) {
                    console.log(err);
                    axmq.request = null;
                    axmq.clear();
                    params.callback({
                        errcode: 5001,
                        errmsg: 'System busy'
                    });
                }
            });
        }
    },
    //example
    sample: function() {
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/a'
            });
        });
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/b'
            });
        });
        axmq.append(function() {
            axmq.post({
                url: 'https://www.sample.com/api/c'
            });
        });
        axmq.render();
    }
};

Call example

axmq.sample();

Read More: