Home  >  Article  >  Web Front-end  >  $.Deferred(), solution to asynchronous request problem in for loop

$.Deferred(), solution to asynchronous request problem in for loop

一个新手
一个新手Original
2017-10-07 11:39:261903browse

Problem: There is an array. Each element in the array asynchronously requests the backend to obtain the corresponding content for operation.

var arr=[];for(let i=0;i<arr.length;i++){
    $.post("请求地址",“传递数据”,function(){
         //异步请求后的操作
   })
}

The problem that occurs when using asynchronous requests in a for loop is that asynchronous requests do not block the main program. When the asynchronous request sends out data, the main program may have ended, which brings problems to our program.

How to use asynchronous requests within a for loop while ensuring the execution order of data?

Solution: $.Deferred()

var lives=[……];
var defer = $.Deferred(); 
defer.resolve($("#aa").append("没有意义")); //该句为必须的,即使什么也不需要操作
$.each(lives,function(i,e){  
  defer = defer.then(function () {  
      return $.ajax({      //进行异步请求操作
        url:"请求地址",  
        type:&#39;post&#39;,
        data:{            //异步请求的数据
          "username":lives[i].username,
          "userId":lives[i].id,
        },
        dataType: "jsonp",
        success:function(data){  
          //异步请求后的操作
        }  
    })
  });  
});

In addition, there are many related contents about $.deferred()

The above is the detailed content of $.Deferred(), solution to asynchronous request problem in for loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn