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

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

一个新手
Release: 2017-10-07 11:39:26
Original
1935 people have browsed it

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(){
         //异步请求后的操作
   })
}
Copy after login

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){  
          //异步请求后的操作
        }  
    })
  });  
});
Copy after login

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!

Related labels:
ask
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template