0

I want to do an AJAX call in a loop with below code.

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

I debugged the code, the log were wrote five times then ajax were executed and the passing parameter i is 4. I doubt the reason is this is an asynchronous call. Then how to modify the code to make it synchronous? I know jquery can do it with setting async, but how to write it in plain javascript without jquery? Thx.

Behemoth
  • 5,389
  • 4
  • 16
  • 40
kk luo
  • 549
  • 1
  • 9
  • 22
  • 3
    so, you want synchronous AJAX? ... or, in other words ... JAX - since the first A in AJAX === Asynchronous - it's in the name! – Bravo Aug 13 '21 at 04:56
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – coagmano Aug 13 '21 at 05:21

1 Answers1

3

The best way to use the for loop construct with asynchronous code, but have it behave like synchronous code (which is assumed by a for loop) these days is to use async/await syntax.

Rewrite your ajax_DatabaseAccessor.query to return a promise (for example, you can use fetch if you are doing an HTTP request) and to be an async function. For example, let's say it was defined like this:

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 use it from your for loop, so we get something like:

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

The point is the answer to your question, if understood or interpreted most charitably, is to look into fetch, async/await, due to its ability to play nicely with for loops. You may also sometimes come across situations where you want to write an awaitable function -- in which case it will help to know how to create a Promise and knowing that a promise is something you can await on will help as well.

Dharman
  • 30,962
  • 25
  • 85
  • 135
keyvan
  • 2,947
  • 1
  • 18
  • 13