H
H
hello_world_6662021-06-23 20:04:57
AJAX
hello_world_666, 2021-06-23 20:04:57

How to stop the loop before ajax is done?

Hello, how to stop the loop before ajax execution and continue after execution? The response of one cycle is about 5 seconds, there can be up to 40 cycles, it is necessary that the browser does not freeze.

jsonData.checkList.forEach(function(data) {
$.ajax({
    type: 'POST',
    url: '/action/action.php',
    data: data,
    success: function(response) {
        var jsonData = JSON.parse(response);
            .......
        }
    });
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-06-23
@Kozack

In JavaScript, a loop forcan wait for the result of a promise at each iteration.

for (data of datas) {
  await fetch( ... ) 
}

N
Nadim Zakirov, 2021-06-24
@zkrvndm

As easy as pie. Run in console:

for (key in jsonData.checkList) {

  var response = await $.ajax({
    type: 'POST',
    url: '/action/action.php',
    data: jsonData.checkList[key],
    dataType: 'json' // Указываем, что ответ надо сразу распарсить, как JSON
  });
  
  console.log('Получены данные:');
  console.dir(response);
  
}

When using in code, don't forget to wrap the loop in an asynchronous function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question