简体   繁体   English

如何等待jQuery ajax请求在循环中完成?

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

I have that code : 我有那个代码:

for (var i = 0; i < $total_files; i++) {
  $.ajax({
    type: 'POST',
    url: 'uploading.php',
    context: $(this),
    dataType: 'json',
    cache: false,
    contentType: false,
    processData: false,
    data: data_string,
    success: function(datas) {
      //does something
    },
    error: function(e) {
      alert('error, try again');
    }
  });
}

It uploads images very well but the problem is that I can't find a way to upload the images one by one, I tried to put the option async to false but it freezes the web browser until all images are uploaded which is not what I want, I want to emulate somehow this "async : false" option to perform the same thing but without freezing the web browser. 它上传的图片非常好,但问题是我找不到逐个上传图片的方法,我试图将选项async设置为false但它冻结了网页浏览器,直到所有图片都上传不是我的想要,我想以某种方式模拟这个“async:false”选项来执行相同的操作但不冻结Web浏览器。

How to do this ? 这该怎么做 ?

You can create an array of promises so that once all promises are resolved you can run your all done code. 您可以创建一个承诺数组,以便在解决所有承诺后,您可以运行all done代码。

var promises = [];
for (var i = 0; i < $total_files; i++){ 
   /* $.ajax returns a promise*/      
   var request = $.ajax({
        /* your ajax config*/
   })

   promises.push( request);
}

$.when.apply(null, promises).done(function(){
   alert('All done')
})

DEMO DEMO

Populate an array with each call and call the next item when the previous is done. 使用每个调用填充数组,并在完成上一个调用后调用下一个项目。

You could try something like that: 你可以尝试这样的事情:

    window.syncUpload = {

        queue : [],

        upload : function(imagesCount) {

            var $total_files = imagesCount, data_string = "";

            /* Populates queue array with all ajax calls you are going to need */
            for (var i=0; i < $total_files; i++) {       
                this.queue.push({
                    type: 'POST',
                    url: 'uploading.php',
                    context: $(this),
                    dataType: 'json',
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: data_string,
                    success: function(datas) {
                    //does something
                    },
                    error: function(e){
                        alert('error, try again');
                    },
                    /* When the ajax finished it'll fire the complete event, so we
                       call the next image to be uploaded.
                    */
                    complete : function() {
                        this[0].uploadNext();
                    }
                });
            }

            this.uploadNext();
        },

        uploadNext : function() {
            var queue = this.queue;

            /* If there's something left in the array, send it */
            if (queue.length > 0) {
                /* Create ajax call and remove item from array */
                $.ajax(queue.shift(0));
            }


        }

    }

Just call it using syncUpload.upload(NUMBER_OF_IMAGES); 只需使用syncUpload.upload(NUMBER_OF_IMAGES)调用它;

For jQuery 3.x+ and modern browser that support native Promise , Promise.all could be used this way: 对于jQuery 3.x +和支持本机Promise现代浏览器, Promise.all可以这样使用:

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. 如果您的文件已经存储在列表中,那么您可以使用map而不是循环。

var fileList = [/*... list of files ...*/];

Promise.all(fileList.map(file => $.ajax({
      /* your ajax config*/
})))
.then(responseList => {
   console.dir(responseList)
})

I would try jQuery.when so you can still use asynchronous call but deferred, something like : 我会尝试jQuery.when所以你仍然可以使用异步调用但延迟,如:

jQuery(document).ready(function ($) {
    $.when(
        //for (var i = 0; i < $total_files; i++) {
            $.ajax({
                // ajax code
            })
        //}
    ).done(function () {
        // perform after ajax loop is done
    }); 
}); // ready

EDIT : ajax iteration should be done outside $.when and pushed into an array as proposed by charlietfl 's answer. 编辑 :ajax迭代应该在$.when .when之外完成并按照charlietfl的回答推荐到数组中。 You may use an (asynchronous) ajax call and defer it inside $.when though, see JSFIDDLE 您可以使用(异步)ajax调用并将其推迟到$.when .when中,但请参阅JSFIDDLE

In one statement with jquery 在jquery的一个声明中

$.when.apply(null, $.map(/*input Array|jQuery*/, function (n, i) {
   return $.get(/* URL */, function (data) {
     /* Do something */
   });
})).done(function () {
  /* Called after all ajax is done  */
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM