I am trying to use Promises but I don’t know if in this case, are useful.
$.getJSON("url", "data", function(json) {
json.forEach(function(item) {
//do something
$.get("url", "data", function(response) {
//MAKE SURE THIS BODY IS SOLVED BEFORE RELOOP???
});
})
})
The only way I found is to use ajax with async
as false
.
Is there a way to solve this?
Maybe using Promises for example? I tried to think a way to use Promises in a foreach
loop but didn’t find any solution.
I tried this one:
$.getJSON("url", "data", function(json) {
json.forEach(function(item) {
//do something
when($.get("url", "data") {
//do something
})).done(function(response){
//do something
});
})
})
But it doesn’t work. foreach
always relooped.
2
Answers
This may be of interest to you… As you wish to perform many ajax request one by one in a loop.
Using
await
in anasync
function, you can wait for an ajax resquest to complete before doing the next one.Below, I used
$.getJSON
in afor
loop… And the console logs clearly show that each request where made one by one.The
$.ajax()
,$.post()
,$.get()
,$.getJSON()
, etc. all are returning a promise. Soawait
can be used. Instead of using the callback function, you have to assign theresponse
to a variable.as in:
instead of:
— That is working in CodePen since the SO snippets are squarely blocking any ajax request.
As an alternative, you could try re-constructing your data from outer-call to build an array and make use of a function to reflect the looping mechanism and initiate each iteration when the previous inner-call finishes (successfully or not).
Check this out. Might this be a viable solution for you?