(1) Promise
Promise means promise. (it's something that will happen in the future)
(1) What is promise?
- In terms of purpose:
(1) promise is mainly used for asynchronous computing.
(2) You can queue asynchronous operations, execute them in the desired order, and return the expected results.
(3) promise can be passed and manipulated between objects to help us deal with queues. - Grammatically:
Promise is an object from which messages for asynchronous operations can be obtained.
Promise provides a unified API, and various asynchronous operations can be processed in the same way - Executor means executor
(2) What are the characteristics of promise objects?
-
(1) The state of the object is not affected by the outside world.
Promise object represents an asynchronous operation and has three states:
pending (in progress)
Fully completed
rejected (failed)
Only the result of asynchronous operation can determine the current state, and no other operation can change this state. -
(2) Once the state changes, it will not change again. This result can be obtained at any time.
There are only two possibilities for the state of Promise object to change:
From pending to fulfilled
From pending to rejected
As long as these two situations occur, the state will solidify, will not change again, and will maintain this result all the time.
If the change has occurred, you can add a callback function to the Promise object and get the result immediately. This is completely different from events. The characteristic of events is that if you miss it and listen again, you won't get results.
(3) Promise's disadvantages?
- (1) Promise cannot be cancelled. Once it is created, it will be executed immediately. It cannot be cancelled halfway.
- (2) If the callback function is not set, the error thrown by Promise will not be reflected to the outside.
- (3) When it is in pending status, it is impossible to know which stage it has reached (just started or about to be completed)
(4) Promise basic usage?
ES6 specifies that Promise object is a constructor used to generate Promise instances.
const promise = new Promise(function(resolve, reject) { // ... some code if (/* Asynchronous operation succeeded */){ resolve(value); // Called when the asynchronous operation is successful, and the result of the asynchronous operation is passed as a parameter } else { reject(error); // Called when the asynchronous operation fails, and the result of the asynchronous operation is passed as a parameter } }); promise.then(function(value) { // Both functions accept the value passed out by the Promise object as an argument. // success / / when the operation succeeds, call the first function }, function(error) { // Failure / / call the second function when failure occurs }); explain: (1) promise Constructor that accepts a function as an argument. (2) This function has two more parameters and accepts resolve and reject These two parameters. (3) resolve and reject It's also a function resolve Functions: take Promise The state of the object from pending Become resolved, Called when the asynchronous operation is successful, and the result of the asynchronous operation is passed as a parameter.!!! reject Functions: take Promise The state of the object changes from pending Become rejected, Called when the asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter.!!!
(5) Promise will be executed immediately after it is created?
componentDidMount() { let p = new Promise((resolve,reject) => { console.log('1') resolve(); }) p.then(result => { console.log('2') }) console.log('3') } // Execution results: // 1 // 3 // 2 explain: In the code above, Promise Execute immediately after creating a new one, so the first output is 1. then, then The callback function specified by the method will not be executed until all synchronization tasks in the current script have been executed, so 2 the final output.
(6) Encapsulate an ajax request with Promise
-
Ajax
ajax is short for Asynchronous JavaScript and XML (Asynchronous JavaScript and XML)
AJAX can make web pages update asynchronously by exchanging a small amount of data with the server in the background, which means that a part of the web page can be updated without reloading the whole web page. -
XMLHttpRequest object
Instantiate object: const xmlhttp= new XMLHttpRequest()
- open(method,url,async)
xmlhttp.open("GET","test1.txt",true); open(method,url,async) // Specify the type of request, URL and whether to process the request asynchronously // method: type of request; GET or POST // url: the location of the file on the server // async: true (asynchronous) or false (synchronous)
- send(string)
xmlhttp.send(); send(string) // Send the request to the server. string: Only for POST request
- setRequestHeader(header,value)
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // xmlhttp.setRequestHeader("Accept", "application/json"); setRequestHeader(header,value) // Add an HTTP header to the request. // Header: Specifies the name of the header // Value: Specifies the value of the header
- responseText
- responseXML
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; responseText // Get the response data in string form. responseXML // Get the response data in XML.
- onreadystatechange event
onreadystatechange: Store the function (or function name) whenever readyState This function is called when the property changes. readyState come into being XMLHttpRequest Status of. Changes from 0 to 4. // 0: request not initialized // 1: Server connection established // 2: Request received // 3: Request processing // 4: The request has completed and the response is ready status // 200: "OK" // 404: page not found
Complete example:
const getJSON = function(url) { const promise = new Promise(function(resolve, reject){ const handler = function() { if (this.readyState !== 4) { // Return before completion. readyState has 0, 1, 2, 3 and 4 states return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); //The parameter of the reject function is usually an instance of the Error object, indicating the Error thrown; } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); }); return promise; }; getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) { console.error('Error ', error); });