Tips for ensuring JavaScript code runs in a specific sequence

On my webpage, I have implemented a feature where users can click a button to fetch data using an xhr get request. During the loading and parsing of this data, I want to display a loading message that will be replaced with the actual data once it is ready. I am using Dojo libraries and prefer not to include jQuery or any other external libraries.

Here is a simplified version of how I have set it up:

HTML

<div id = "clickMe"> Click Me! </div>
<div id = "results" class = "hidden">
    Please wait while we retrieve the results
</div>

CSS

.hidden {display: none;}

Javascript

// Attach function to click me div
var clickMe = document.getElementById('clickMe');
clickMe.addEventListener('click', getResults, false);

function getResults () {
    // Display the loading message while results are being fetched
    var resultsDiv = document.getElementById('results');
    resultsDiv.classList.remove('hidden');

    // Fetch and parse the data using a standard dojo.xhrGet method
    var displayResults = getData();

    // Show the fetched data in resultsDiv, replacing the loading message
    resultsDiv.innerHTML = displayResults;
}

The issue I am facing is that the getResults function waits for the getData function to complete before removing the 'hidden' class and displaying the results div. This results in the user skipping the loading message and directly seeing the data, even if there is a delay in data processing. Interestingly, if I introduce an alert in the middle, it forces the function to pause and the loading message is shown:

function getResults () {
    // Display the loading message while results are being fetched
    var resultsDiv = document.getElementById('results');
    resultsDiv.classList.remove('hidden');

    // The loading message is displayed when this alert is included
    alert("Hello world!");

    // Fetch and parse the data using a standard dojo.xhrGet method
    var displayResults = getData();

    // Show the fetched data in resultsDiv, replacing the loading message
    resultsDiv.innerHTML = displayResults;
}

I have tried replacing the alert with console.log, but the loading message does not show up. I also attempted setting up the data fetching as a callback function within displaying the loading message, but that did not work either. Even when using the get request with sync: true or sync: false, the loading message is not displayed.

How can I ensure that the loading message is visible while waiting for the getData function?

Edit:

Here is the getData function. I have tried both with and without sync:

function getData() {
    var targetUrl = //some url;
    var restResponse;

    dojo.xhrGet({

        url: targetUrl,
        sync: true; // no difference when this is omitted

        load: function(result) {
            restResponse = result;
        }

    });

    // Parse the rest response - fairly long function so I won't paste it here
    var parsedResponse = parseResult(restResponse);

    return parsedResponse;
}

Answer №1

If you want to enhance your coding skills, I highly recommend delving into the world of writing asynchronous code and mastering the use of dojo/Deferred.

Instead of using the method getData, consider renaming it to loadData and

loadData: function() {
    return xhr('', {...}); // this function will return a deferred object
}

function fetchResults () {
    var resultsContainer = dom.byId('results');
    domClass.remove(resultsContainer, 'hidden');

    loadData().then(function(displayedResults) {
        resultsContainer.innerHTML = displayedResults;
    });        
}

Expand your knowledge on dojo/Deferred here

Answer №2

Utilizing deferreds and promises in jQuery is a powerful tool.

Explore more about it here. When working with ajax requests, you can chain them together efficiently (especially since jQuery 1.8).

var promise1 = $.ajax("/myServerScript1");

function retrieveData() {
    return $.ajax("/myServerScript2");
}

promise1.then(retrieveData).then(function(myServerScript2Data){
  // Both promises have been successfully resolved
});

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

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

Hide the menu when it is clicked in a React component

My objective: Implementing a functionality to close the Navbar by clicking the button placed within it. Despite my efforts, I am unable to make it work. I would appreciate any guidance on what I might be missing! Below is the code for my Navbar: import R ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

The navigation in Framework 7 is causing issues with the on-click functionality

Utilizing the framework's built-in formToJSON() function, I have been able to retrieve form values. By utilizing a click event, I am able to log the values. $$("#query-submit").on("click", function () { var queryForm = app.formToJSON("#query-form ...

What is the best way to obtain the id of an HTML element that is generated within jQuery code?

Typically, data is retrieved in HTML by storing the html in the html file. In my case, however, I create the html element inside jQuery. So, how do I call out the div id? How can I replace document.getElementByID ("edit").innerHTML=.... when the element i ...

Unable to recognize click event within the ng-click function

I need to identify when a click event occurs on an SVG element, specifically on a g element within the SVG element. Currently, I have created this JSFiddle The ng-click function is working properly, but unfortunately, the click event is not being detecte ...

What is the best way to modify an array's property in order to achieve the desired outcome when using json_encode?

Expected Result ['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50'] The output I am receiving is as follows: ["'#ff0000','#4caf5 ...

vue-dropzone fails to create thumbnails when a file is added

I am facing an issue where I want to upload files that are already stored on my server to the Dropzone. Despite searching extensively through both vue-dropzone and regular dropzone documentation, as well as various GitHub issues for solutions, I have not b ...

In the readmore.js script, position the "readmore" link within a div instead of outside of it

I have added annotations that vary in length, so I am looking to integrate the readmore.js plugin. To ensure uniform sizing for all annotations (even empty ones), I need to set a minimum height for the div container. <annotation> <div style="wi ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

React-dnd enhances the functionality of the MUI tree view

I've been using a Material UI v4 Treeview with react-dnd and everything works smoothly. However, when I recently upgraded to MUI v5 Treeview, the drag functionality stopped working - the item is no longer draggable. After comparing the two TreeItem im ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...

The method of utilizing React with Redux to display component properties

I am currently trying to include my common component in my main.js file Successfully implemented this However, when attempting to print my Redux data values in the common component, I created a method called handleClickForRedux to handle this task. Even af ...

What is the best way to alter something based on the current date?

My goal is to dynamically change a message based on how close a specific date is. The objective is to update an element of a webpage to display "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 ...

What is the best way to delete HTML classes that were generated by a function?

Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the ...

What is the reason behind assignments being completed faster than doing nothing?

class RandomObj { constructor() { this.valA = ~~(Math.random() * 255 + 0.5); this.valB = ~~(Math.random() * 300 + 0.5); } } const array1 = new Array(100000); for (var i = 0; i < 100000; i ++) { array1[i] = n ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...