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.