A guide to creating a synchronous AJAX call using vanilla JavaScript

I am trying to make multiple AJAX calls in a loop using the code below.

for (var i = 0; i < 5; i++) {
  console.log(i);
  ajax_DatabaseAccessor.query("CheckInt", i, loadQuery);
  function loadQuery(data) {
    alert(DWRUtil.toDescriptiveString(data, 2));
  }
}

After debugging the code, I noticed that the log was written five times before the AJAX calls were executed, and the parameter being passed is always 4. This discrepancy makes me believe that this is due to the asynchronous nature of the call. How can I modify the code to make it synchronous? I am aware that jQuery has an option to set async to false, but I want to achieve this in plain JavaScript without relying on jQuery. Thank you.

Answer №1

If you want to make asynchronous code behave like synchronous code when using a for loop, the best approach these days is to utilize the async/await syntax.

To achieve this, you can modify your ajax_DatabaseAccessor.query function to return a promise by turning it into an async function. For example:

let ajax_DatabaseAccessor = {}
ajax_DatabaseAccessor.query = async (idk, someIdea, someSelector) => {
    let response = await fetch("some_resource/"+idk+"/"+someIdea)
    let data = await response.json();
    return someSelector(data)
}

Now that your code is awaitable, you can incorporate it within your for loop as follows:

for(var i = 0 ;i<5;i++){
  let myDescriptiveString = await ajax_DatabaseAccessor.query("CheckInt", i,  (data)=>DWRUtil.toDescriptiveString(data, 2));  
}

In essence, the solution to your query suggests exploring the use of fetch and async/await due to their compatibility with for loops. It may also be beneficial to understand how to create an awaitable function by working with Promise objects, which are capable of being awaited on.

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 need the inner HTML of the AJAX response to be displayed in the <tr>

My table row (tr) contains a select option field and a free input field. When I choose an option, the field is populated with data via AJAX. https://i.sstatic.net/9hpG7.png However, when adding a new row, I want the input field to be filled in the new ro ...

Storing data with ElectronJS

I am currently working on an Electron JS and React JS offline application. One of the initial steps in my launch process involves loading a large file that is over 1 GB in size and cannot be divided. This causes a delay of approximately 50-60 seconds whi ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

What could be the reason for the error message when using rs.send with a string input?

I'm a beginner in node and express, and I was trying to create an HTML form that takes two numbers and displays the result using "express" and "node". However, when I use rs.send(result), I encounter the following error: https://i.sstatic.net/FcUNJ.p ...

Can you explain the differences between offsetHeight, clientHeight, and scrollHeight for me?

Have you ever wondered about the distinction between offsetHeight, clientHeight, and scrollHeight? What about offsetWidth, clientWidth, and scrollWidth? Understanding these differences is crucial for working effectively on the client side. Without this kn ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

What could be causing the "keyframes method" in my css to not function correctly?

When working on the keyframes section, my computer seems to be having trouble recognizing the from part. Ideally, it should display in blue with the opacity command appearing in grey. Unfortunately, neither of these styles are appearing correctly and I&apo ...

The parsing of Jquery ajax xml is not working as expected

Upon parsing my XML using the code below, everything was working fine until I added a review node. $(document).ready(function generatexml(){ $.ajax({ type: "GET", url: "data/concerts.xml", dataType: "xml", ...

Is there a way to prevent the Material UI Chip component from appearing when there is no content present?

I have developed an application that pulls content from an API and displays it on the screen. Within this app, I have implemented a Material UI Card component to showcase the retrieved information, along with a MUI Chip component nested within the card. &l ...

Refreshing a div using Php and ajax at specific intervals

Can I load the div values automatically when the page loads along with after a time interval? How can I achieve this? <script type="text/javascript> $(document).ready(function() { setInterval(function(){ $("#Te ...

Is there a substitute for useState in a Next.js server component?

With my static site at , the only interactive feature being the dark mode toggle, I understand that using useState is not feasible in a server component. export default function RootLayout({ children }: { children: React.ReactNode }) { const [darkMode, ...

Move the absolute div by sliding it to the left from 120% to -10px

I want to move an absolute positioned div from the left side of the screen to -10px on button click. Here's my attempt so far, but it's not working as expected. Javascript/jQuery $('.button').click(function() { $(this).parent().f ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Retrieving data and selecting tables using jQuery

Currently, I have an HTML table displaying various available times for scheduling purposes. My goal is to allow users to click on a specific time slot and retrieve both the column header (staff person's name) and the value of that cell (the time). Aft ...

Unable to write to file due to permission restrictions from EPERM. Will delete existing file and create a new one. This action

I am encountering an issue with my file system function that involves deleting a file and creating a new one with updated data. The error occurs randomly, not consistently, happening approximately every other time the code runs. Below is my current impleme ...

Converting an array into a string, transitioning from PHP to JavaScript

Hey everyone, I'm currently working on passing an array to a JavaScript file and encountering this error: An exception has been thrown during the rendering of a template ("Notice: Array to string conversion"). What I need is: data: ['2017/7&a ...

implementation of an Ajax countdown timer on an ASP.NET webpage

My website has a timeout of 5 minutes. I want to display the countdown in minutes and seconds, like this: 4 minutes and 10 seconds remaining I attempted to use the code below to accomplish this: <asp:Timer ID="Timer1" runat="server" ...

Specify the location of the resize button (corner)

Scenario : At the bottom of the page, there is a resizable textarea, However, having the resize button at the bottom-right corner does not provide the best user experience (try it out), Issue : I am wondering if there is a way to move the resize butt ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...