Asynchronous loading has always been a headache for me, the undergraduate phase of the asynchronous synchronous communication has made me very confused. But after contacting the asynchronous load in JS I really realized that the so-called asynchronous loading is like a customer service center, and each worker has a workflow line. Below I will detail the implementation method of Pronise.
Promise is an object that is used to pass an asynchronous operation message. It represents an event in the future that will know the result (success or failure).
Features of the Pomise object include:
(1) The state of the object is unaffected by the outside world.
There are 3 states, Pendind, resolved, and rejected. Only the result of an asynchronous operation can determine which state is currently present, and no other operation will change that state.
(2) Once the state change will not change, at any time can get this result.
There are only two promise state changes, one from pending to resolved and the other from pending to rejected. As long as one of them happens, the state freezes and no other action can change the state.
Disadvantages of the Pomise object include:
(1) Once created, it will be executed immediately and cannot be canceled.
(2) If the callback function is not set, the internal error cannot be thrown
(3) When in the pending state, it is not possible to know the current progress to which stage.
Compatibility:
Promise just let our current JS change a form of implementation, more in line with the thinking angle and way of programming. Therefore, with a specific conversion, we can also make it possible to support a low-version browser that does not support promise. You can try to introduce the following JS on the page:
<script src= "Http://s3.amazonaws.com/es6-promises/promise-0.1.1.min.js" ></script>
Basic usage
Ajax implementations of Promise objects
varGetjson =function(URL) {varPromise =NewPromise (function(Resolve, reject) {varXHR =NewXMLHttpRequest (); Xhr.open ("GET", URL); Xhr.onreadystatechange=handler; Xhr.responsetype= "JSON"; Xhr.setrequestheader ("Accept", "Application/json"); Xhr.send (); functionhandler () {if( This. readyState! = 4){ return; } if( This. Status = = 200) {Resolve ( This. Response); }Else{Reject (NewError ( This. statustext)); } } }); returnpromise;} Getjson ('./post.json '). Then (function(JSON) {Console.log ("Content" +json);}).Catch{Console.log ("Something went wrong.")}
.... Not finished updating
The promise of JavaScript