The website is not delaying for the synchronous web service response

When I call a sync web service on my website, the results are not being waited for.

I am calling the function loadExtLayout within the loadLayout function, and then calling loadLayout in other functions on the website.


    HTTPRequestService.prototype.loadExtLayout = function(pathToLoad){
        logManager.IHM_LOG_INFO("BEGIN HTTPRequestService loadExtLayout call pathToLoad="+JSON.stringify(pathToLoad));
        var loadResult = null;
        $.ajax({
            async:false,
            method: "GET",
            url: pathToLoad
        }).done(function(result){
                loadResult = result;
            }).fail(function(jqXHR, textStatus){
                loadResult = null;
                logManager.IHM_LOG_ERROR(new Error().stack+": "+"Error loading layout : " + pathToLoad + " (" + textStatus + ")\n");
               });
        logManager.IHM_LOG_INFO("END HTTPRequestService loadExtLayout call");
        return loadResult;
    }


GenericLayoutController.prototype.loadLayout = function(layoutName){
    logManager.IHM_LOG_INFO("BEGIN loadLayout");
    var loadResult = false;
    var layoutContent = null;
    try {
        var httpService = new HTTPRequestService(this.AppId);
        if(httpService != null){

            layoutContent = httpService.loadExtLayout(layoutName);
            console.log("layoutContent :" + layoutContent); 
            if ((layoutContent != null) && ($("#window_"+ this.AppId + "_" + this.WndId).attr("patternname") == this.patternName)) {
                $("#window_"+ this.AppId + "_" + this.WndId).empty();
                $("#window_"+ this.AppId + "_" + this.WndId).html(layoutContent);
                loadResult = true;
            } else if( layoutContent == null ){
                logManager.IHM_LOG_ERROR("Error loading layout !");
            }
        } else {
            logManager.IHM_LOG_ERROR("Error unable to create HTTPRequestService object : httpService is null !");
        }
    } catch(e) {
        loadResult = false;
        logManager.IHM_LOG_ERROR(new Error().stack+": "+e+"\n");
    }
    logManager.IHM_LOG_INFO("END loadLayout");
    return loadResult;
}

Answer №1

When utilizing the ajax parameter 'async: false', it is necessary to use a callback function for success instead of promises. This is because 'then' operates asynchronously and the 'return' statement executes before the promise retrieves data from the server.

let data = null;
$.ajax({
   async:false,
   method: "GET",
   url: pathToLoad,
   success:(response)=>{data = response}
}); 
return data;

Alternatively, you can handle it asynchronously:

HTTPRequestService.prototype.loadExtLayout = function(pathToLoad){
    logManager.IHM_LOG_INFO("BEGIN HTTPRequestService loadExtLayout call pathToLoad="+JSON.stringify(pathToLoad));

    let loadResult = new Promise((resolve,reject)=>{
        $.ajax({
            async:false,
            method: "GET",
            url: pathToLoad
        }).done(function(result){
                resolve(result);
            }).fail(function(jqXHR, textStatus){
                reject(textStatus);
                loadResult = null;
                logManager.IHM_LOG_ERROR(new Error().stack+": "+"Error loading layout : " + pathToLoad + " (" + textStatus + ")\n");
               });
    });
    logManager.IHM_LOG_INFO("END HTTPRequestService loadExtLayout call");
    return loadResult;
}

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

Oops! The Python TextBlob library couldn't locate the resource at 'tokenizers/punkt/english.pickle'

A similar issue was encountered by someone else, but they were able to solve it by downloading the necessary packages. I have already downloaded the packages, yet I am still experiencing the error. Oddly enough, I can run the code in the terminal without ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

How can I rename attribute values in a dropdown menu and ensure they work properly?

I'm facing an issue with my code. How can I store the option values in a database when they have numbering like value="1" or value="2"? Can I change it to something like value="1000" and have the other select box change to value="250" when selected? ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Error message: UnhandledPromiseRejectionWarning in (Node.js, Express.js, MongoDB) - TypeError occurs when trying to access an undefined 'username' property

I'm struggling to fetch and print the post's author from mongodb using client-side code. Unfortunately, my current code is throwing an error. It is a fullstack javascript code and despite my efforts in searching for a solution, I couldn't fi ...

What is the best way to trigger a JavaScript function whenever a field reaches a specific length?

I need to update a function that currently triggers when the user clicks or tabs out of the employee_number field. My goal is for it to run whenever the length of the entered numbers reaches 6, without requiring the user to leave the field. When I attempte ...

Tips on creating adaptable images for mobile viewing

My coding conundrum involves the use of two columns - one for an image and the other for a description of that image. However, when viewing my site on mobile devices, the image is cut off at only half its height. Adjusting both columns to col-sm-6 results ...

When sharing a Laravel AJAX request, it does not include any arguments

I'm encountering difficulties passing arguments through a Laravel AJAX request. Despite numerous similar inquiries, none seem to offer a solution tailored to my specific issue. Below are my Laravel routes: Route::get('workerAjax', function ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Tips for deleting a duplicate identifier within an li element that possesses a particular class through javascript

I need help removing duplicate IDs from list items with a specific class. For example, in the following list, there are duplicates IDs (small, medium) and I want to remove the IDs with the class "size". How can I achieve this? <ul id="bulk"> ...

Issue with React conditional display not functioning properly post user input into a form

Thank you in advance for your help. I am working on a component that displays a button based on the const results. However, I noticed that when I insert "Balaton," the button only appears after I add another character to the string. So the string becomes ...

Generating prime numbers in Javascript

My attempt at generating the prime numbers less than 20 using my current knowledge is as follows: let arr = []; for (let x = 3; x <= 20; x++) { for (let i = 20; i > 0; i--) { if (x % i !== i) { arr.push(x) } } console.log(arr) ...

What is the origin of function parameters in javascript?

I have implemented the following code: handleOwnerMode = ownerChecked => { this.setState(prev => ({ ownerChecked, showOwner: !prev.showOwner})) // this.setState(prev => ({ ownerChecked: !prev.ownerChecked, showOwner: !prev.showOwner ...

Executing a callback in AngularJS after multiple HTTP requests have been completed using a forEach loop

I am trying to update multiple items within a foreach loop by sending HTTP requests, and I need a callback once all the requests are complete. Despite searching on Stack Overflow, I haven't found a solution that works for me. Here is the snippet of m ...

Troubleshooting MySQL Database Insertion Errors caused by Dynamic Forms

<body> <?php $con = mysqli_connect('localhost','root','','cash'); $query = "SELECT DISTINCT category FROM cash"; $result = mysqli_query($con,$query); $dropDownList = &apo ...

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Query MySQL with PHP using a variable found in HTML

I need help with creating a PHP script that can search my database for parts using a generated part number from an HTML page and display the price in a table cell. Below is the Ajax script and variable I am using: var Row = document.getElementById("test ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...