1.promise
1.1 promise concept
- promise is a solution for asynchronous programming that is more reasonable and powerful than the traditional solution, callback functions and events.
- Simply put, it is a container that holds the results of an event (usually an asynchronous operation) that will end in the future.
- Syntax, promise is an object from which messages for asynchronous operations can be obtained. Promise provides a unified API, and asynchronous operations can be handled in the same way.
Features of 1.2 promise
There are only two types, and a promise object can only be changed once. Whether it becomes success or failure, there will be a result data. Success result data is generally value, and failure result data is generally called reason.
- Operation successful: pending - > fulfilled/resolved,
- Operation failed: pending - > rejected
Asynchronous callback nesting
promise
Parameter 1: resolve parameter: bring out the value that returned the success
Parameter 2: reject parameter: bring out the value that failed to return the response
ES6 specifies that a promise object is a constructor used to generate a promise instance. By return ing an instance of a promise object inside the function, you can use the properties and methods of the promise to proceed to the next step.
1.3 promise method
- The hen() method separates the original callback writing and executes the callback function by chain invocation after the asynchronous operation is completed.
.then() has two parameters (two parameters are two functions, the first is the successful result value, and the second is the failed result value).
The first parameter of then() represents a function that captures successful results
The second parameter of then() represents the function that captures the result of the failure - Like the then() method, a new promise object is returned, which is mainly used to catch exceptions that occur during asynchronous operations.
- all() promise contains an array of n promises, indicating that if a new promise is returned, only promises succeed and fail if one fails.
- race: the result state of the first promise completed is the final result state
// promise method var p = new Promise(function(resolve){ setTimeout(function(){ resolve('Eat hot pot') },2000) }).then(ele=>{ console.log(ele); return getLai(); }).then(ele=>{ console.log(ele); })
Convert ajax into promise form:
function promise(options){ return new Promise((resolve,reject)=>{ var xhr = new XMLHttpRequest(); var params = formdata(options.data); if(options.type=='GET'){ xhr.open(options.type,options.url+'?'+params,options.isAsync); xhr.send(); } if(options.type=='POST'){ xhr.open(options.type,options.url,options.isAsync); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(params); } xhr.onreadystatechange = function(){ if(xhr.readyState==4){ if(xhr.status==200){ resolve(xhr.responseText) }else{ reject('error') } } } }) } function formdata(obj){ var arr = []; for(var k in obj){ arr.push(k+'='+obj[k]) } return arr.join('&') }
Call:
promise({ type:'GET', url:'', date:{}, isAsync:true, }).then(data=>{ console.log(data); return promise({ type:'GET', url:'', data:{}, isAsync:true, }) }).then(data=>{})
2-1.jsonp
2.1 What is homology
If two pages have the same protocol, domain name, and port, they belong to the same source, and if only one page is different, it is a different source.
http://www.example.com/dir/page.html http://www.example.com/dir2/other.html: homologous http://example.com/dir/other.html: different sources (different domain names) http://v2.www.example.com/dir/other.html: different sources (different domain names) http://www.example.com:81/dir/other.html: different sources (different ports) https://www.example.com/dir/page.html: different sources (different protocols)
2.2 What is Homology Policy
Homology policy is a security feature of browsers. Client scripts from different sources cannot read and write to each other's resources without explicit authorization.
2.3 Purpose of Homology Policy
The homology policy is to protect the security of user information and prevent malicious websites from stealing data.
2-2jsonp Cross Domain
Principle of jsonp: There are many tags on the page, such as SRC and href, which are not affected by the homology policy.
Some tags are naturally cross-domain capable, such as img, link, iframe, script
jsonp is using
jsonp consists of two parts: callback functions and data, which are functions that should be called on the page when a response arrives. The name of the callback function is usually specified in the request. The data is the JSON data passed into the callback function
- Write server-side request addresses from different sources in the src attribute of the script tag
<script src="www.example.com"></script>
- The server-side response data must be a call to a function, and the data that is actually sent to the client needs to be a parameter to the function call.
const data = 'fn({name: "Zhang San", age: "20"})';
- At Client Global Scope
function fn(data){}
- Processing data returned from the server within the fn function
Overall implementation ideas:
- Client needs to pass function name to server side
- Turn the sending of script requests into dynamic requests.
function jsonp(options){ var oSc = document.createElement('script'); oSc.src = options.url; document.body.appendChild(oSc); oSc.onload = function(){ this.remove(); }}
Encapsulation of jsonp
function jsonp(options){ // Create script var oSrc = document.createElement('script'); // window[fn]: mount FN function in global scope // Convert the incoming function under the window object var fn = 'myfn' + Math.random().toString().replace('.',''); // fn random function name window[fn] = options.success; oSrc.src = options.url+'?callback='+fn+'&'+getParams(options.data); document.body.appendChild(oSrc); oSrc.onload = function(){ this.remove(); } } function getParams(obj){ var arr = []; for(var k in obj){ arr.push(k+'='+obj[k]); } return arr.join('&') }