Ajax request implementations that do not use callback functions (async and await simplify callback function nesting)

Source: Internet
Author: User
Tags try catch

In regular server-side programming, such as a crawler, the process of sending an HTTP request blocks the entire execution process until the HTTP request response completion code continues to execute, with PHP as an example

$url = "http://www.google.com.hk"; $result file_get_contents ($url); Echo $result;

When the code executes to the second line, the program is caught waiting until the request is complete, and the program continues to run down the HTML output that will be crawled. The benefit of this approach is that the code is concise, the running process is clear and easy to maintain. The disadvantage is that the running speed of the program depends on the response time of the HTTP request, which affects the running efficiency of the program. However, because of the nature of the Web application itself, this problem is avoided, the program relies on the results of the HTTP response and ensure that its own rapid response between the contradiction between the two, certainly can not be balanced.

However, in the case of client programs or non-HTTP applications, there is no similar conflict, in Java or C # client programming, this problem is usually open two threads each. In JavaScript, however, because the language itself does not support multithreading, this type of problem is solved by using a callback function.

Take the simplest front-end Ajax request as an example

function (response) {        Console.log ("2");}); Console.log ("1")

Code First output 1, then output 2, the entire program execution process is not blocked due to HTTP requests, callback function scheme perfectly solves the problem. However, this is just the simplest example of a callback function, if the callback function nesting many layers?

function (response) {    function  (response        ){function  (response) {            Console.log (response);     });});

The deeper the callback nesting, the more difficult the code to run the logic, if the above code on the basis of mixed with some complex business logic, the code will be extremely difficult to maintain, then encountered the problem of the shear constantly confused feeling will certainly make people red eyes dozens. Although this callback nesting scenario is rare in web front-end development, it is common in the NODEJS server-side development area. How to overcome this problem? If you write in PHP, that's a very easy thing to do.

$response file_get_contents ("Data1.json"); $response 1 =   file_get_contents($response["url"]); $response 2 =   file_get_contents($response 1["url"]); Echo $response;

The logic of the code is much clearer when implemented in the scenario of sending HTTP requests in PHP. In ancient times, JavaScript wanted to implement Ajax in this way, which was a dream, but when JavaScript was upgraded to the ES6 version, it could be done in a specific way. This is called "writing asynchronous code in a synchronous way", but I think it's easy to confuse people, and you can call it a "synchronous notation" because the asynchronous execution inside is hidden. To achieve this, you must use the two keywords async and await. In two keywords is es7 category, ES6 is not supported, but can be used by a specific tool to use these two keyword code to ES6 code to execute, such as Typescript and Babel, the code example used in this article is implemented by typescript . The underlying mechanism for async and await is not detailed here, so as not to delay the length of the article, here is the effect of the two key words can be explained. First the above in JavaScript implementation of multi-layered nested back call synchronous way to rewrite, the code is as follows

AsyncfunctionAjax (URL) {return NewPromise (function(Resolve, reject) {let ajaxsetting={url:url, success:function(response) {Resolve (response); }, Error:function() {Reject ("Request Failed");     }} $.ajax (ajaxsetting); });} AsyncfunctionRun () {Let response1= await Ajax ("Data1.json"); Let Response2= await Ajax (response1["url"]); Let Response3= await Ajax (response2["url"]); Console.log (RESPONSE3);} //Do not blockRun ();

The code consists of two functions, Ajax and run, which encapsulate the jquery Ajax so that it can get Ajax response without using a callback function. When a function is declared as an async type, if the function is to have a return value, and the return value is to be obtained in a callback function, then the return result of the function can only be a promise object, just like the Ajax function of the example, the return value if it is a different type, it will not achieve the desired effect. The parameters of the promise constructor are a function, and the resolve and reject are the two parameters of the function, and the two parameters themselves are the function types, both of which have important meanings, and here they function to return the contents of the AJAX response. Resolve indicates that a value is returned in a normal state, and reject represents a value that returns an exception. By traditional encoding, reject can be seen as throwing an exception, like a throw "request failed", so that it can be captured outside of a function call with a try catch. Pass the value out why go through these two parameters? Because you can't do it, just imagine, what is the meaning of using the return statement in the Ajax callback function? Therefore, it can only be changed to throw the return value to the external caller via promise. So the first key point to using async and await is

When a function is to get an asynchronous result, a function can be declared as an async type, the return value of the function is set to the Promise type object, and the resolve and reject in promise are used to return the result to the Async function as a return statement of the normal function.

How do you use the async type function? There are two methods, one is direct call, directly call the function before the Async keyword is ignored, the call function returns the result is a promise object, promise on how to use it here does not go into the drill, roughly is like the following wording

Ajax ("Data1.json"). Then (function(response) {...});

Or in the form of a callback function, the significance of improving the code is not reflected.

Another method is to add the await keyword when calling a function, and the meaning of an await is to receive values passed by resolve and reject in the Promise object in the Async function, and unless the resolve and reject functions are called in the callback function, Otherwise the code has been blocked there? In other words, the call to resolve and reject is used to inform the await to wait for the end and the code can continue to execute. This is not the way to try to achieve a synchronous writing? The difference with PHP is that it is more than three concepts of await, async, promise, but without taking into account the inner workings of the code, there is no difference between the execution process and the synchronization. It is important to note that if you need to use an await call in a function, the function must also be declared as an async type, or the program will not function properly if the compilation is wrong. So, the second point is

Await is used to wait for the execution of the resolve and reject functions in the Promise object, and to assign the arguments passed by the two functions as return results to the variables, as in the example code in the Run function. , await must be sandwiched between two async, one is the function of the await call, and the other is the function that the await is located in.

As for the reject in promise, which is used to throw exceptions, outside of the await call can be captured using a try catch, the code is as follows

function run () {    try  {        = await Ajax ("Data1.json");         = await Ajax (response1["url"]);         = await Ajax (response2["url"]);        Console.log (RESPONSE3);     Catch (ex) {        console.log (ex);    }}

This article is purely to explain the role of await and async? How do I use it? As for in-depth knowledge of the details, interested students can go to Ruan Feng's blog to learn, attached to the link address

Http://www.ruanyifeng.com/blog/2015/05/async.html

This article starts with the public number "bring you a good code", please pay attention to get more original share.

Ajax request implementations that do not use callback functions (async and await simplify callback function nesting)

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.