Looking to implement a Javascript AJAX queue system for handling cross-domain JSONP requests. Seeking guidance on how to effectively accomplish this

I have a JavaScript code that I need to convert into a queue system. Currently, the code looks messy with long chains of requests being made in a specific order. Please note that my function requests return JSON objects and setting async to false is not an option for cross-domain JSONP calls. Calls must be made in a particular sequence and jQuery queues are not suitable.

var customers;
var orders;
var products;

function GetCustomers(){
    $.ajax({
        url: somecrossdomainurl?calback=GetCustomerCallback,
        dataType: 'jsonp',
        async: false
    });
}

function GetCustomerCallback(data){
    customers = data;
    GetCustomersOrder();
}

function GetCustomersOrder(){
    $.ajax({
        url: somecrossdomainurl?calback=GetCustomersOrderCallback,
        dataType: 'jsonp',
        async: false
    });
}

function  GetCustomersOrderCallback(data){
    orders = data;
    GetOrderProducts();
}

function GetOrderProducts(){
    $.ajax({
        url: somecrossdomainurl?calback=GetOrderProductsCallback,
        dataType: 'jsonp',
        async: false
    });
}

function  GetOrderProductsCallback(data){
    products = data;
    DisplayCustomersAndOrder();
}

function DisplayCustomersAndOrder(){
   //loop through customer, order, products and display info
}

Any suggestions on how to improve this code?

Answer №1

This code showcases the implementation of an asynchronous queue using promises. You can find the original source code here.

Although written in TypeScript, it can be easily converted to pure JavaScript with minimal effort.

If you prefer not to continue on error, there are simpler alternatives like chaining each call with `then`.

Please note: This implementation requires JQuery version 1.8 or higher for proper functionality of the `then` method.

export class AsyncExecutionQueue{

    private tail: JQueryPromise = $.Deferred().resolve();

    public enqueue(cmd:()=>any): JQueryPromise {

        console.log("Queuing Command");
        var next = $.Deferred();
        var client = $.Deferred();
        this.tail.always(() => {

            try {

                var result = cmd();
                if (result.done && result.fail) {
                    result
                    .done(client.resolve, next.resolve)
                    .fail(client.reject, next.resolve);
                }
                else {
                    client.resolve(result);
                    next.resolve();
                }
            }
            catch (e) {
                client.reject(e);
                next.resolve();
            }
        });
        this.tail = next;
        return client;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

What is causing the scripts to fail when I attempt to press a button?

Clicking on the button is supposed to slowly reveal phone numbers on the page. Here are the HTML Codes: <span id="show-phone-numbers" class="btn btn-success"> <i class="fe fe-phone-call"></i> Show Phone Nu ...

Typing in Text within Kendo Textbox using Protractor

I'm encountering an issue with Protractor while trying to input text into a Kendo TextBox. The error message I receive is "ElementNotVisibleError: element not visible". Interestingly, when the text box is clicked on, the "style="display: none;" change ...

Set a default value for a FormControl within react-bootstrap

When working with my email address, I utilized the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44362125273069262b2b30373036253404746a76706a71">[email protected]</a>. In order to specify the initial value chosen ...

The hyperlink does not appear to be functioning properly within a specific Div on the iPad. Interestingly, this issue does not persist when using other

Apologies if I am posting this question in the wrong place. I have a webpage (built with asp.net/vb) where each section is contained in divs within a Bootstrap grid. Through the code behind, I am attaching onclick events to each set of divs to perform sp ...

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...

What is the process for writing code in a recursive manner?

I'm in the process of converting these code snippets into smaller ones using recursion. However, I've hit a roadblock while trying to implement a for loop. The dictionary I am working with is: var structure = []; and it has the following structu ...

What steps should I take to host a Node.js application on a subdomain using an apache2 VPS?

Currently, I have a Node.js application that I would like to host on a subdomain using my VPS. The VPS is running apache2 and the Node.js app utilizes Express. Despite trying both Phusion and following this tutorial, I have been unsuccessful in getting i ...

How does the useEffect React hook perform its comparison process?

One of my favorite JavaScript expressions is: []==[] // false Let's now explore what the React documentation says about skipping side effects: React allows you to skip applying an effect if certain values have not changed between re-renders. To a ...

Close Tooltip when Ajax content is loaded

While working with jQuery tooltip, I encountered an issue. I have content loaded on a DIV element that is supposed to show a tooltip when I hover over an image map element within this DIV. Everything works fine until I click on one of the image map element ...

Assign the value selected from a dropdown menu to a PHP variable for MySQL

Is there a way to adjust the variable $Category in the following mysql query based on the selection made in the dropdown list? This seems like a straightforward task, but I'm having trouble figuring it out. It would be really helpful if the page coul ...

Customizing the appearance of Twitter Bootstrap based on the AngularJS input class $invalid

I'm struggling with getting error messages to display properly in my Bootstrap form when using AngularJS. I followed the instructions on this link: but I still can't figure out what I'm doing wrong. Any advice? Thanks <div class=" ...

Populate DataTables with data from JSON or JavaScript arrays and objects

Using jQuery(html), I was populating a table with data but now I am attempting to limit the displayed rows by switching the table to datatables. The data structure looks like this: dataArray = [{ id: 1, props: { abc: 123, def: 456 ...

I can't seem to get db.collection.findOneAndUpdate() to work properly when using the

User Data { "_id" : ObjectId("60c012cc35fd3c596d61e72d"), "tags" : [ "react", "node", "js" ], "title" : "This is the updated title", "description" : "I am a skil ...

The jQuery bookmarklet in the djangobyexample book is completely unresponsive

As I work my way through Django By Example, I came across a chapter where a jQuery bookmarklet is created within a Django app. This allows users to easily save jpg images from websites into their user profile area within the Django app. Although the tutor ...

Why is the jQuery datepicker malfunctioning when nested within ng-repeat in AngularJS?

I am currently facing an issue with the jquery ui date picker in my AngularJS application. The date picker is functioning correctly outside of any ng-repeat loops, but it stops working when placed within one. <input type="text" class="form-control date ...

Stream-Awesome #12: The Return of Duplexer in Nodesville

For days, I've been attempting different methods to solve this exercise. It's frustrating because no matter what I try, I keep encountering a "write after end" error. But here's the thing - I'm using the "end" event and not writing anyt ...

Tips for customizing the appearance of popup windows

I want to enhance the appearance of my popup window by applying a different format for opening it. How can I style it so that it looks visually appealing when the popup window opens? You can find below the source code I am working with: HTML: <div onM ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

JavaScript Delayed Redirection

I'm attempting to launch opera from the command line and have it redirect to a page after 30 seconds. Here's what I currently have: C:\Programme\Opera\opera.exe -newpage javascript:function%20func1(){window.location.href='htt ...