How to wait until jQuery ajax request finishes in a loop?

后端 未结 5 814
终归单人心
终归单人心 2020-11-27 02:42

I have that code :

for (var i = 0; i < $total_files; i++) {
  $.ajax({
    type: \'POST\',
    url: \'uploading.php\',
    context: $(this),
    dataType:         


        
5条回答
  •  再見小時候
    2020-11-27 03:25

    For jQuery 3.x+ and modern browser that support native Promise, Promise.all could be used this way:

    var promises = [];
    for (var i = 0; i < $total_files; i++) {
       // jQuery returns a prom 
       promises.push($.ajax({
          /* your ajax config*/
       }))
    }
    
    Promise.all(promises)
    .then(responseList => {
       console.dir(responseList)
    })
    

    If your files are already stored in a list then you could use map instead of a loop.

    var fileList = [/*... list of files ...*/];
    
    Promise.all(fileList.map(file => $.ajax({
          /* your ajax config*/
    })))
    .then(responseList => {
       console.dir(responseList)
    })
    

提交回复
热议问题