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

Source: Internet
Author: User

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

If you want to post-process the results returned by a request using an ajax request, it is best to use a synchronous request. The following describes the methods and differences between synchronous and asynchronous processing in js. Do not miss out if you are interested.

When an asynchronous request is used, it is sometimes necessary to return the result of the asynchronous request to another js function. In this case, the asynchronous request is not returned, the js function that sends the request has completed subsequent operations, that is, the return has been executed, which will result in the return result being a null character.

 

Conclusion: To send the returned results after processing the ajax request, it is best to use synchronous requests.

 

For example, in the following example, the returned result is incorrect because the ajax asynchronous request has not been executed and the function has already executed return,

The Code is as follows:

Function fn (){

 

Var result = "";

 

$. Ajax ({

Url: 'Your url ',

Data: {name: value },

Cache: false,

Async: true,

Type: "POST ",

Success: function (data ){

Do something ....

 

Result = ....

}

 

// Processing the data returned by ajax may also cause errors

 

Return result;

}

 

1 asynchronous request method:

The Code is as follows:

$. 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 Method

The Code is as follows:

$. Ajax ({

Url: 'Your url ',

Data: {name: value },

Cache: false,

Async: false,

Type: "POST ",

DataType: 'json/xml/html ',

Success: function (result ){

Do something ....

}

});

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.