Summary of methods and differences between synchronous and asynchronous processing in js

  • 2020-03-30 01:04:11
  • OfStack

When asynchronous request is used, it is sometimes necessary to return the result of asynchronous request to another js function. In this case, the result of asynchronous request will be returned without waiting asynchronous request. The js function where the request is sent has completed the subsequent operation, that is, the return has been executed.

Summary: to process the results returned by sending a request after using an ajax request, it is best to use synchronous requests.

For example, the following example might not return the correct result because the function has already returned the ajax asynchronous request,
 
function fn(){ 

var result = " "; 

$.ajax({ 
url : 'your url', 
data:{name:value}, 
cache : false, 
async : true, 
type : "POST", 
success : function (data){ 
do something.... 

result = .... 
} 

//Handling the data returned in ajax can also cause errors

return result ; 
} 

1. Asynchronous request mode:
 
$.ajax({ 
url : 'your url', 
data:{name:value}, 
cache : false, 
async : true, 
type : "POST", 
dataType : 'json/xml/html', 
success : function (result){ 
do something.... 
} 
}); 

2. Synchronous request mode
 
$.ajax({ 
url : 'your url', 
data:{name:value}, 
cache : false, 
async : false, 
type : "POST", 
dataType : 'json/xml/html', 
success : function (result){ 
do something.... 
} 
}); 

Related articles: