Ajax requests can form a pyramid of doom when multiple asynchronous calls are structured

My JavaScript application requires making an ajax call and potentially more calls based on the previous response. Currently, I have implemented this using a somewhat cumbersome pyramid of doom:

function startParentArray(id) {
    getIssueDetail(id).success(function(data) {
        var source = $("#parenttemplate").html();
        var tpl = Handlebars.compile(source);
        processResponse(data, tpl);       
    });
}

function processResponse(data, tpl) {
    if (data.issue.parent) {
        nextparent = data.issue.parent.id;
        makeAjaxCall(nextparent, tpl);
    }
}

function makeAjaxCall(parentId, tpl) {
    getIssueDetail(parentId).success(function(data) {
        $("#parenttable").append(tpl(data.issue));
        if (data.issue.parent) {
            makeAjaxCall(data.issue.parent.id, tpl);
        }
    });
}

Is there a cleaner way to achieve this behavior, perhaps using a while-loop or other approach?

Answer №1

If you're in search of a solution, consider exploring promises. Personally, I find this resource quite helpful. Don't forget that jQuery also offers a similar feature with $.Deferred, even though it may not adhere to the standards set by A+ promises

Credit for this information goes to Kris Kowal's q

Promises have the ability to prevent the "Pyramid of Doom," where code stretches out horizontally faster than it progresses vertically.

Answer №2

I haven't had a chance to run this code myself, but it looks like it could do the trick

function initializeParentArray(id) {
    var template = $("#parenttemplate").html();
    var compiledTemplate = Handlebars.compile(template);

    processArray(compiledTemplate, id);
}

function processArray(compiledTemplate, parent){
    getIssueDetails(parent).success(function(data) {
        $("#parenttable").append(compiledTemplate(data.issue));
        if(data.issue.parent) {
            processArray(compiledTemplate, data.issue.parent.id);
        }
    });
}

Since you're repeating the same logic in all of your success callbacks, this method might simplify things for you.

Answer №3

If you want to make multiple AJAX requests in jQuery, you can utilize the $.when() method

$.when( $.ajax( "/data1.php" ), $.ajax( "/data2.php" ) )
      .done(function( response1, response2 ) {
      // Handle the responses from data1.php and data2.php here
});

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

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

Ways to show a component based on a specific condition being met using react and javascript

On every page, the layout component is rendered. My goal is to achieve the following: on /items page *Display Layout component only if user is admin *Do not display Layout component if user is non-admin Below is my code snippet: function Main() { con ...

The hit detection algorithm seems to be malfunctioning, and the reason behind it is unclear. (Using Javascript/Processing

I am a beginner in game programming and programming in general. In the past, I have created a clone of "Flappy Bird" and some other games using the hit detection algorithm from the Mozilla Developer Network here. Currently, I am facing an issue while tryi ...

The importance of .hash in this jquery function explained

I utilized a jQuery function from someone else and tweaked it to fit my needs, however, I am struggling to grasp how it actually operates. Specifically, the line var content = this.hash.replace('/', ''); Can anyone offer an explanation ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

AngularJS - Interactive web pages powered by controller scripts

I am experiencing an issue with my AngularJS page where a popup is not displaying correctly. The popup HTML is fetched dynamically from the server using an AJAX request, including a new controller and relevant AngularJS code. The problem arises when the ch ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Tips for managing and modifying information with a dropdownlist in asp.net core mvc and angular js

In my asp.net core MVC project, I am incorporating AngularJs to manage two dropdown lists and a textbox. While the textbox functionality for saving and editing data works well, I am facing issues with resetting the dropdown lists after posting data and not ...

Close the Bootstrap Modal by clicking the back button within SweetAlert

**How can I close a Bootstrap modal when clicking the back button in SweetAlert? I have tried using modal.hide() but it's not working. I am using Bootstrap version 5 and even checked their documentation with no luck. Does anyone know how to achieve th ...

Clickable link unresponsive on parallax-enhanced webpage

Currently, I am utilizing Zurb foundation's Manifesto theme for creating a parallax scrolling landing page. The anchor tag is essential for the scrolling effect on this page, causing a conflict when regular anchor links are included. Here is the HTML ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Example when a specific $scope.apply() is needed:

I am currently delving into the world of Angular and experimenting with different ways to learn how it functions. One of my projects involves creating a simple application where users can add new entries through an HTML interface, store them in a SQLite da ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

Ensure to check the input file for null values before proceeding

My task involves working with an input file: Razor: @Html.TextBox("archivo", "", new { type = "file",id = "archivo" } Html: <input id="archivo" name="archivo" type="file" value=""> I am trying to detect if the value of the input is null when a b ...

Retrieve, process HTML table information using Ajax from an external server or website domain

In order to demonstrate: :the html table data source = "example.com/html_page_source" (tableid="source") :an xml file created from the specified table data = "pretendco.com/xml_built_from_html_table I am seeking guidance on how to build an xml file from ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Encountering a Cross-Origin Resource Sharing (CORS) error when attempting to process payments using Node.js

I am trying to process a payment using PayPal SDK. My frontend is built with AngularJS and my backend uses Node.js. In my frontend, I simply make a call to a route on my Node server like this: $http.post('/paypal/pay', cart) I have CORS config ...