What is the best way to implement object-oriented programming to have an asynchronous AJAX request return a value upon completion?

I need assistance with the code snippet provided below.

My goal is for the 'airported' object to generate a list of airports. However, I am struggling to retrieve the data once the each loop has completed its iteration in finding 'li's in the list.html file (retrieved via ajax).

The airported object utilizes an instance of the Airport class. I prefer not to have complex code scattered throughout my application. All I want is to invoke 'airport.list()' and receive the desired list of airports.

The list.html file is included for reference purposes only. There is no need to extensively analyze it. Despite this, I must utilize it and cannot opt for a clean JSON format or any similar alternative.

Javascript

   function Airport() {

        this.list = function() {

            var airportList = []

            var promise = this.data();

            promise.success(function(data){

                var list = data;

                var listSize = $(data).find('li').size();

                $.each($(list).find("li"), function(key,val) {

                    airportList.push(val);

                    if(listSize == key+1) {

                        console.log(airportList);

                        return false;

                    }

                });

            })

            return airportList;

        };

        this.data = function() {

            return $.ajax({
                url: "/list.html"
            })

        };

    }

    var airported = new Airport();

    console.log('airported', airported.list());

list.html

<html>
<head></head>
<body>
<div id="listautocomp" style="background:white">
    <ul id="ulSuggest">
        [Airport list items omitted for brevity]
    </ul>
</div>
</body>
</html>

Answer №1

It seems that the promise won't work synchronously in this scenario since you are returning before receiving the data. To address this, consider passing a callback function to handle the data retrieval.

If you want to make the promise asynchronous, follow the example below:

function Airport() {

    this.list = function(callback) {

        var airportList = [];

        var promise = this.data();

        promise.success(function(data){

            var list = data;

            var listSize = $(data).find('li').size();

            $.each($(list).find("li"), function(key,val) {

                airportList.push(val);

                if(listSize == key+1) {
                    console.log(airportList);
                    return false;
                }

            });

            if(typeof callback === "function") {
               callback(airportList); //the actual return happens here asynchronously
            }

        })

        //return airportList; //the return value is empty at this point

    };

    this.data = function() {

        return $.ajax({
            url: "/list.html"
        })

    };

}

var airported = new Airport();

airported.list(function(airportList){
     console.log('airported', airportList);
});

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

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Executing Javascript in a Bootstrap 4 modal using Rails

I am working on a Rails 5.1 application where I'm implementing a patient record creation functionality using Ajax within a form using coffeescript/JS. The code I have been using for this task works seamlessly: _form.html.erb <div class="modal fad ...

I am looking to view all products that belong to the category with the ID specified in the request, and have red-colored stocks

Within my database, I have defined three mongoose models: Product, Category, and Stock. The Product model contains two arrays - categories and stocks, each including respective category and stock ids. My goal is to retrieve all products where the category_ ...

Tips for updating the content of a div with the click of another div

Is there a way to dynamically change the content of a div upon clicking on a menu item? Here is the current layout for reference: https://i.stack.imgur.com/nOnlQ.png Below is the CSS and HTML code snippet: body { background-color: #555657; ...

In the world of Node.js and Java, the concepts of "if"

Here is a code snippet that I am working with: var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; if (randFriend == admin) { //Do something here } else if (randFriend != admin) { client.removeFriend(randFriend); } I am tr ...

The issue with the max-height transition not functioning properly arises when there are dynamic changes to the max-height

document.querySelectorAll('.sidebarCategory').forEach(el =>{ el.addEventListener('click', e =>{ let sub = el.nextElementSibling if(sub.style.maxHeight){ el.classList.remove('opened&apos ...

What is the best way to pass JavaScript object literals from a Node.js server to the frontend browser?

In Node, I am working with JavaScript object literals containing methods in the backend. For example: const report = { id: 1, title: 'Quarterly Report for Department 12345', abstract: 'This report shows the results of the sales ...

IE9 encounters an error when using jQuery's .remove() function

While testing my website in IE9 using Firebug Lite, I encountered an issue. When attempting to run a basic command to remove a div, I received an error saying "TypeError: Object expected". The command I used was: $("#drag-hoverbox_you").remove(); Interes ...

Lazy loading images in a grid using React's react-lazy-load component

In my React application, I have a grid of images. To show these images in the div grid, I am utilizing sprites where each set of 10 divs uses a single URL to display the thumbnail. With approximately 16000 thumbnails to showcase, I decided to implement rea ...

jQuery Bootgrid Pagination issue: Unable to successfully pass the current page element

My experience with jQuery Bootgrid has been a bit challenging as I encountered 2 problems related to Pagination. Below is the JavaScript code that I have been working with: The data method in the code below seems to be defaulting to GET, even though I ...

The function angular.factory does not exist

Hey there! I am encountering an error in the title related to my factory. Any suggestions on how I can resolve this issue? (function (angular,namespace) { var marketplace = namespace.require('private.marketplace'); angular.factory(&apo ...

Exploring date range options in Highcharts for viewing data from a specific selected date

Using HTML, JS, and Controller public function graph(Request $request) { $statistics = DiraStatistics::where('date_access',$request->date)->get(); $question_asked_sum = $statistics->sum('question_asked'); $low_ ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...

How can I integrate a Google Maps instance into my Rails views?

I have a file named my_app.js.coffee and it includes the following Google Maps setup: map = undefined initialize = (map) -> myOptions = center: new google.maps.LatLng 39.729001, -94.902342 zoom: 3, mapTypeId: google.maps.MapTypeI ...

Javascript has trouble processing data coming from an HTML input field

I am struggling to make my JavaScript code work with the input from my HTML input tag. The purpose of this program is for the user to input a number, and then the program will determine whether the number is positive, negative, or zero. Below is the code ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...

Adjusting a Vue Slider with a changing value

Currently, I am utilizing the Vue Slider component from this source. My goal is to enhance the functionality of the slider by increasing it to the next index and beyond. The issue lies in the fact that the current implementation increments by 1, as the val ...