Explore synchronous and asynchronous, Ajax, callback functions, Promise

Table of Contents

1. Introduction to Ajax

1. The concept of asynchronous and synchronized

2. Why is it said that synchronous requests will “reload the entire page”, while asynchronous requests “will only load part of the page”. What does this mean?

3. Functions and advantages of Ajax

Function

Advantage

4.Why is Ajax called asynchronous javascript and xml?

2.Ajax operation process

ask

response

3. Quick Start

Interpretation

Functions of the XMLHttpRequest object

4. Axios asynchronous library

Interpretation

1.Callback function

2. Callback Hell

3.Promise

(1) Promise objects have the following two characteristics:

(2) Return value of Promise object

(3) Calling method after asynchronous execution of Promise object


1. Introduction to Ajax

AJAX(Asynchronous JavaScript And XML) : Asynchronous JavaScript and XML

1. The concept of asynchronous and synchronized

Synchronization: After executing a function or method, it waits for the system to return a value or message. At this time, the program is blocked and will only continue after receiving the returned value or message. Execute other commands.

As soon as the server receives the client’s request, it responds immediately, so that the client can get the result in the shortest time. However, if there are multiple clients, or if one client sends frequent requests, the server cannot process them synchronously, which will cause Chungsai.

Asynchronous: After executing the function or method, there is no need to wait blockingly for the return value or message. You only need to delegate an asynchronous process to the system. Then when the system receives the return value or message, the system The asynchronous process of delegation will be automatically triggered to complete a complete process.

In an asynchronous request, when the server receives the request, it does not process it immediately. Instead, it puts the request into the task queue (or message queue) to wait for processing. This queuing operation does not process the request directly, but queues the request to wait for server resources and processing power. When the server is idle, the request will be taken out of the queue through the event loop or other mechanisms for actual processing. The processing of asynchronous requests is deferred and non-blocking.

?How to understand the bottom layer?

Similar to multi-threading, multiple threads run at the same time to compete for CPU resources, but what is different from multi-threading here is that there is a priority

Synchronous request>Asynchronous request

As long as a synchronous request is initiated, asynchronous requests will never be executed. The CPU will not issue thread resources to asynchronous, and synchronization will only use the main thread. Therefore, multiple synchronous requests will be executed in the same thread in order. Yes According to the request order, there are not multiple synchronous requests competing for resources concurrently, but simple single-thread execution.

And if there are multiple asynchronous requests issued at the same time, the CPU will allocate thread resources to each request, including the main thread, for true parallel processing. When the CPU resources are insufficient, there will be concurrent competition for thread resources.

2. Why is it said that synchronous requests will “reload the entire page”, And asynchronously “only part of the page will be loaded”, what does this mean?

In fact, when you open a page in the browser, the page is continuously rendered and loaded in the background, with the same priority as mentioned above.

Synchronous request>Rendering

As long as a synchronous request is initiated, rendering will not be performed (thread resources will not be allocated to the rendering operation), so in this case the rendering will stop, so you will feel the “loading” feeling. When the synchronous request process ends, the rendering will continue. ,At this time, there are new response resources, different pages are displayed, and asynchronous will not stop the rendering, which is equivalent to them being “level”. Under normal circumstances, asynchronous requests will not compete for the resources of the rendering thread. , when the asynchronous request ends, a new response resource is returned, and a different page is displayed.

At this time you may ask: Doesn’t this mean that the synchronous request will not reload, but will re-render the page and cause the page to be reloaded? But aren’t asynchronous requests always rendering? So why does it say that the entire page cannot be reloaded asynchronously?

In fact, these statements confuse the concepts of rendering and reloading the page. Rendering and reloading the page are two different concepts. Rendering the page is a continuous process. During the process, from the initial loading of the page to the user’s interaction with the page, operations such as partial refresh and asynchronous requests may be performed, but the entire page will not be completely reloaded. Reloading the page means reloading the entire page content, including re-obtaining resources, re-parsing HTML, re-calculating styles, re-laying out elements, and re-drawing. Generally, it will not be reloaded. So in this case, both synchronous requests and asynchronous requests are not actually reloading the page but re-rendering!

In fact, if you want to reload the page, both synchronous and asynchronous requests can be updated through JavaScript to jump to other web pages to reload the page, or you can use the reload page method in JavaScript to load this web page.So whether it is a synchronous request Both asynchronous requests and JavaScript can be used to load part or the entire page. Because asynchronous requests can be executed in parallel, they are often used to update part of the page, resulting in a better user experience. If they are all synchronous requests, it’s like if I shoot CF, I can only shoot without moving, or I can only move without shooting, just like a personal computer.

3. Functions and advantages of Ajax

function

1. Initiate an asynchronous request: It is often used to exchange data with the server and update part of the web page without reloading the entire page, such as: searching for Lenovo, verifying whether the user name is available, etc. wait…

2. Receive response data and update HTML through JavaScript code

Advantages
  1. No plug-in support is required, the original js can be used.
  2. Good user experience (You can update data without refreshing)
  3. Reduce the burden on the server
  4. Disadvantages: Search engine support is not enough, because the data is not on the page and cannot be searched by search engines.

4. Why is Ajax called asynchronous javascript and xml

AJAX mainly provides an asynchronous communication mechanism (that is, the function of initiating asynchronous requests and transmitting data), and how to process the data is completed by JavaScript. XML is a commonly used data format used to transmit and exchange data. However, it is now more commonly used to use JSON (JavaScript Object Notation) as the data exchange format because JSON is more lightweight and easier to process.

So why is Ajax called asynchronous javascript and xml? Ajax just initiates asynchronous requests and transmits data. Data processing is still javascript, and the transmission data type is json or xml. This definition does not mean that Ajax replaces the functions of javascript and xml, but the request Has the method been changed to asynchronous?

This understanding is incorrect

AJAX does not mean the realization of “asynchronous JavaScript and XML”, but a technology that uses JavaScript and XML or other formats to realize the entire asynchronous communication process. I call Ajax an asynchronous communication tool, in which the data processing and operation logic is composed of JavaScript takes care of that, and the data transfer format can be XML, JSON, or other formats.

2.Ajax operation process

request

1. The front end sends the data submitted by the user in JSON format through Ajax and sends an asynchronous request to the background

Get user-entered data in a front-end script and convert that data to JSON format using JavaScript. Then, use the JSON string as a parameter to send an asynchronous request to the backend through Ajax. The background Java script can obtain the string parameter through the HttpServletRequest object.

2. After the backend receives the data submitted by the frontend, it inserts the data into the database through JDBC

After the Java backend receives the JSON string sent by the front end, it uses Java’s built-in JSON library to convert the JSON string into a Java object, then uses JDBC to connect to the database and insert the data into the database.

response

1. The backend connects to the database through JDBC and retrieves the required data

Use Java to write back-end scripts, connect to the database through JDBC (Java Database Connectivity), read the required data, and add the data to the Java data structure.

2. Convert the retrieved data into JSON format and return it to the front end

The backend uses Java’s built-in JSON library (such as Jackson, GSON, etc.) to convert the data into JSON format, and then returns the JSON string to the front end through the HttpServletResponse object.

3. The front end uses AJAX to obtain the JSON data returned by the background, and parses the data to render it into HTML

The front-end uses AJAX technology to initiate an asynchronous request to the background and obtains data in JSON format from the background. The front end can use native JavaScript or third-party libraries (such as jQuery, etc.) for AJAX requests and data parsing. From the parsed data, the front end can use HTML tags to generate page elements.

3. Quick Start

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //1. Create core object
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    //2. Send request
    xhttp.open("GET", "http://localhost/Ajax_Demo/ajax_test1");
    xhttp.send();

    //3. Get response
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 & amp; & amp; this.status == 200) {
            alert(this.responseText);
        }
    };

</script>
</body>
</html>

Interpretation

1. Create core objects

First, use if (window.XMLHttpRequest) to determine whether the current browser supports the XMLHttpRequest object. This is a built-in object used for sending HTTP requests, which provides functionality for communicating with the server. If the current browser supports the standard XMLHttpRequest object, a new XMLHttpRequest instance will be created through new XMLHttpRequest() and assigned to the variable xhttp

2. Send request

Then, use the xhttp.open() method to open a connection to the server, specifying the GET request method and requested URL:

xhttp.open("GET", "http://localhost/Ajax_Demo/ajax_test1");

The GET request method is used here, and the requested URL is http://localhost/Ajax_Demo/ajax_test1.

Next, call the xhttp.send() method to send an asynchronous request to the server:

xhttp.send();

3. Get response

Listen to the onreadystatechange event through value:

  • 0: The request is not initialized, the XMLHttpRequest object has been created, but the open() method has not been called.
  • 1: The server connection has been established and the open() method has been called.
  • 2: The request has been received, the send() method has been called, and the request header information has been received.
  • 3: The request is being processed and the server’s response data is being received.
  • 4: The request has been completed and the response is ready. The complete server response can be obtained.

When the values of readyState and status change, the onreadystatechange event will be triggered so that the response status can be processed. The callback function is executed when the status of the XMLHttpRequest object changes to 4, that is, when the request is completed. In the callback function, we can determine the result of the request based on the value of the status attribute. If status is 200, it means the request is successful. You can pass >responseText or responseXML attribute to obtain the server’s response data.

Function of XMLHttpRequest object

  1. Send asynchronous HTTP requests: You can use the XMLHttpRequest object to send various types of HTTP requests, such as GET, POST, PUT, DELETE, etc. You can set the request URL, request headers, request body, etc.

  2. Receive server response: Through the XMLHttpRequest object, you can monitor the server’s response and obtain the response status code, response header, response body and other information.

  3. Get response data and process data: You can use the XMLHttpRequest object to process the data returned by the server, such as displaying the response data to the page, parsing JSON data, uploading files, etc.

In fact, there are other functions besides this

  1. Use synchronous requests: By default, the XMLHttpRequest object sends an asynchronous request. However, it is also possible by setting the async parameter to false
  2. Sending FormData data: The XMLHttpRequest object can send FormData objects for handling form data with file uploads.
  3. Monitoring progress: You can monitor the progress of uploading and downloading through the onprogress event.
  4. Set request header information: You can set the request header information through the setRequestHeader() method, such as setting the Content-Type of the request.

4.Axios asynchronous library

Axios (axios.js): It is a Promise-based JavaScript library for sending HTTP requests. One of its purposes is to simplify Ajax code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--Introducing the js file of axios-->
<script src="js/axios-0.18.0.js"></script>
<script>
    //1.get request method
    axios({
        method:"get",
        url:"http://localhost/Ajax_Demo/ajax_test3?username=zhangsan"
    }).then(function (resp){
        alert(resp.data);
    })

    //2.post request method
    axios({
        method:"post",
        url:"http://localhost/Ajax_Demo/ajax_test3",
        data:"username=zhangsan"
    }).then(function (resp){
        alert(resp.data);
    })

    //1.get simplified
    axios.get("http://localhost/Ajax_Demo/ajax_test3?username=zhangsan").then(function (resp){
        alert(resp.data);
    })
    //2.post simplification
    axios.post("http://localhost/Ajax_Demo/ajax_test3","username=zhangsan").then(function (resp){
        alert(resp.data);
    })

</script>
</body>
</html>

Interpretation

In the code block, GET and post request methods are used, but the location of the data is different. Get is behind the url, while post is in the data. The axios function is called, passing in a configuration object in which the method attribute is set to “get`` or ``post``,url attribute is set to the requested URL. Then, a Promise object is returned and a callback function is registered to handle the response to the request. In the callback, resp.data represents the data returned from the server, which is displayed in the pop-up window by calling the alert method.

I understand everything from the front, but what is the Promise object and what is the callback function? ? ?

1.Callback function

A function takes another function as a parameter. The called function is called a callback function.

As for application, the comparator method, lambba expression, and callback function used in sorting are a common way to handle asynchronous operations in JavaScript, which can help us get feedback after the asynchronous operation is completed or process the results of the asynchronous operation.

function makeAjaxRequest(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) { // Request completed
      if (xhr.status === 200) { // Response received successfully
        //Call the callback function and pass the returned data
        callback(null, xhr.responseText);
      } else {
        // If the response is not successfully received, call the callback function and pass the error message
        callback(new Error('Request failed'));
      }
    }
  };
  xhr.open('GET', url, true);
  xhr.send();
}

function handleResponse(error, response) {
  if (error) {
    console.error('Request failed:', error);
  } else {
    console.log('Request successful, data returned:', response);
  }
}

//Initiate an Ajax request and pass the callback function
makeAjaxRequest('https://api.example.com/data', handleResponse);

Looking at this Ajax asynchronous request, there is a layer of makeAjaxRequest function nested outside the Ajax code that initiates the asynchronous request. The first parameter is the URL that initiates the request, and the second parameter is the callback function name, xhr.onreadystatechange is assigned to an anonymous function, which will be called when the readyState attribute changes. This function handles the return result of the request by checking the readyState and status attributes. When readyState and status change, the function is automatically called, and then further calls the callback function to respond to the response data. Perform handleResponse operation.

Therefore, the main function of the callback function is to ensure that specific code logic can be executed after the asynchronous operation is completed, thereby more clearly managing the response code of the asynchronous operation

2. Callback hell

When a request depends on the result of the previous request, it is continuously nested, which is very messy and difficult to maintain. It brings a great psychological shadow to programmers, so it is called callback hell.

getUserInfo(function(userInfo) {
  getOrders(userInfo.id, function(orders) {
    getOrderDetails(orders[0].id, function(orderDetails) {
      processOrder(orderDetails, function(processedOrder) {
        saveOrder(processedOrder, function(savedOrder) {
          console.log("Order saved:", savedOrder);
        });
      });
    });
  });
});

Characteristics of callback hell

Code logic becomes deeply nested, making it more difficult to understand and read. In this case, the code becomes less readable and maintainable, and debugging and error handling becomes more difficult.

3.Promise

A solution to the callback hell of asynchronous programs is more reasonable and powerful than the traditional solution - callback functions and events. It is a class provided by ECMAScript 6, which aims to be more elegant. Write complex asynchronous tasks easily.

emmmm,What is ECMAScript 6?

ECMAScript is also a scripting language, abbreviated as ES. It is usually regarded as the standardized specification of JavaScript. ECMAScript6.0 is the next generation standard of JavaScript language. Its goal is to enable JavaScript language to be used to write complex large-scale applications and become an enterprise-level development language. But in fact, JavaScript is an extension language of ECMAScript, because ECMAScript only provides the most basic syntax. In layman's terms, it just stipulates how to write our code, such as defining variables and functions, loops and branches... It just stays at the language level and does not It cannot be used to complete actual functional development in our application.

In a browser environment, JavaScript = ECMAScript + BOM + DOM

Okay, I understand, let’s start introducing Promise objects

(1) The Promise object has the following two characteristics:

1. The state of the object is not affected by the outside world. The Promise object represents an asynchronous operation and has three states:

  • pending: initial state, not success or failure state.
  • fulfilled: means the operation was completed successfully.
  • rejected: means the operation failed.

Only the result of the asynchronous operation can determine the current state, and no other operation can change this state. This is also the origin of the name Promise, which means "commitment" in English and means that it cannot be changed by other means.

2. Once the status changes, it will not change again, and this result can be obtained at any time. There are only two possibilities for the state of a Promise object to change: from Pending to Resolved and from Pending to Rejected. As long as these two situations occur, the state will be solidified and will not change again, and will maintain this result. Even if the change has already occurred, if you add a callback function to the Promise object, you will get the result immediately. This is completely different from an event. The characteristic of an event is that if you miss it and listen again, you will not get the result.

(2) Return value of Promise object

var promise = new Promise(function(resolve, reject) {
    //Asynchronous processing
    // After processing, call resolve or reject
});

When the asynchronous code executes successfully, we will call resolve(...), and when the asynchronous code fails, we will call reject(...)

(3) Calling method after asynchronous execution of Promise object

promise.then(function(data)){

}.catch(function(data)){

});

//When the execution is successful, the returned response data is placed in data,

Improvements to the callback hell above

getUserInfo()
  .then(function(userInfo) {
    return getOrders(userInfo.id);
  })
  .then(function(orders) {
    return getOrderDetails(orders[0].id);
  })
  .then(function(orderDetails) {
    return processOrder(orderDetails);
  })
  .then(function(processedOrder) {
    return saveOrder(processedOrder);
  })
  .then(function(savedOrder) {
    console.log("Order saved:", savedOrder);
  })
  .catch(function(error) {
    console.error(error);
  });

So in summary, axios is a Promise-based HTTP client for sending asynchronous HTTP requests. What it returns is indeed a Promise object, which will be resolved or rejected when the request succeeds or fails.

In your code, the .then() method is used to handle the callback function when the request is successful. The callback function receives a parameter resp, which contains the response data of the request. The response data can be accessed through resp.data, and you can display it to the user in a pop-up window.

Because .then() still returns a Promise object, you can continue to chain call other Promise methods to handle asynchronous operations. You can also use the .catch() method to handle the callback function when the request fails, as well as other processing logic.

This Axios library class simplifies Ajax code in this way.

syntaxbug.com © 2021 All Rights Reserved.