等待完成for循环内调用的所有ajax函数

问题描述 投票:0回答:1

我有一个函数reboot(),预计在for循环中的所有ajax调用完成后调用。

我尝试在for循环内的所有“proceedSaving”完成后调用“reboot”函数。数组值可能会更改为

[1,3], [1,4,5] , [3,4],[2,2,5]

saveSettings{
      for (i in [1,2,5,4]) {
        proceedSaving(i,param1,param2);
      }
      reboot(); //
}

async proceedSaving(i,param1,param2)){
..
 let url = '/ajax/test.php?command=updateUsbPortConfig';
           await performAjaxPostRequest(url, urlParams, saveResponseHandler);
            
}           

function saveResponseHandler(readyState, responseText, responseXml, status){
    if ((readyState == 4) && ((status == 200) || (status == 0))) {
        var response = JSON.parse(responseText);
        
        if (response.status === 'success') {
            
        }
        
    }
}   
javascript ajax for-loop
1个回答
0
投票

只需在包含异步函数的 for 循环中使用“For wait of”

async saveSettings {
  for await (let i of [1, 2, 5, 4]) {
    proceedSaving(i, param1, param2);
  }
  reboot(); //
}

async proceedSaving(i, param1, param2)) {
  ..
  let url = '/ajax/test.php?command=updateUsbPortConfig';
  await performAjaxPostRequest(url, urlParams, saveResponseHandler);

}

function saveResponseHandler(readyState, responseText, responseXml, status) {
  if ((readyState == 4) && ((status == 200) || (status == 0))) {
    var response = JSON.parse(responseText);

    if (response.status === 'success') {

    }

  }
}

© www.soinside.com 2019 - 2024. All rights reserved.