axios
ajax
Cross domain
promise
The jQuery ajax () and axios
LocalStorage etc.
other
axios
Axios: A Promise-based HTTP library that can be used in browsers and Node.js. It has the following features: it encapsulates native XHR; Can be used in Node.js; Provides an interface for concurrent requests; Support the Promise API; Intercepting requests and responses; Cancel the request;
Some advanced uses of Axios, such as JSON auto-processing, are called json.parse if the content-type of the response is found to be JSON. Request interceptor, which can add some operations to all requests; The response interceptor, which can add something to all the responses and even change the content; Different instances can be generated and different configurations can be set for complex scenarios.
Simple use:
axios({
method: 'GET',
url: url,
})
.then(res => {console.log(res)})
.catch(err => {console.log(err)})
Copy the code
There are many ways to write it, you can go to the official documentation
Concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
Copy the code
Interceptor: Intercepts requests or responses before they are processed by THEN or catch.
/ / add request interceptor axios. Interceptors. Request. Use (function (config) {/ / what to do before sending a request return config. }, function (error) {return promise.reject (error); }); / / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / do something to return the response to the response data; }, function (error) {return promise.reject (error); });Copy the code
If you want to remove interceptors later, you can do this:
const myInterceptor = axios.interceptors.request.use(function () {/*... * /}); axios.interceptors.request.eject(myInterceptor);Copy the code
You can add interceptors for custom AXIOS instances
const instance = axios.create(); instance.interceptors.request.use(function () {/*... * /});Copy the code
Error handling
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Copy the code
You can use the validateStatus configuration option to define an error range for a custom HTTP status code.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
Copy the code
Cancel the request using the Cancel token
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else {// handle error}}); axios.post('/user/12345', { name: 'new name' }, { cancelToken: Source.token}) // Cancel the request (the message argument is optional) source.cancel('Operation Canceled by the user.'); CancelToken can also be created by passing an executor function to the CancelToken constructor: const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: New CancelToken(function executor(c) {// The executor function accepts a cancel function as an argument cancel = c; })}); // cancel the request cancel();Copy the code
Note: You can cancel multiple requests using the same Cancel token
Now, the question is, why do we have cancellation requests when we already have them? Why is there a need? We often encounter a problem of repeated clicks during development. Clicking the same button to send requests for several times in a short period of time will increase the burden on the server and consume the performance of the browser, so we need to do an operation to cancel repeated clicks most of the time. In real life, when the Internet speed is not good, if we click a button in the app and there is no response, we will usually wait and click for several times. At this point, the request is repeatedly sent back to the background. This situation will bring a lot of unnecessary requests to the backend server, waste resources. So in this case, we need to cancel subsequent requests. The general idea is:
1: We set up an array, which stores objects one by one. The object contains an Ajax request mark for each Ajax request and the corresponding function to cancel the request.
2: Each time a request is initiated, an interceptor is set up to determine whether the request has already been issued, and if so, the request is cancelled. At the same time, the data information corresponding to the request is recorded in the array.
3: Interceptors should be set before each response to cancel the completed request and delete the relevant data of the corresponding Ajax request in the array.
Code:
import axios from 'axios'; axios.defaults.timeout = 5000; axios.defaults.baseURL =''; let pending = []; // Declare an array to store the cancellation function and ajax identifier for each Ajax request let cancelToken = axios.canceltoken; let removePending = (ever) => { for(let p in pending){ if(pending[p].u === ever.url + '&' + ever.method) { // Execute the function body pending[p].f() when the current request exists in the array; // Execute the cancel operation pending.splice(p, 1); / / the records removed from the array}}} / / HTTP request interceptor axios. Interceptors. Request. Use (config = > {config. Data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/x-www-form-urlencoded' } // ------------------------------------------------------------------------------------ removePending(config); CancelToken = new cancelToken((c)=>{config. CancelToken = new cancelToken()=>{ Pending. Push ({u: config.url + '&' + config.method, f: c}); }); // ----------------------------------------------------------------------------------------- return config; }, error => { return Promise.reject(err); }); / / HTTP response interceptor axios. Interceptors. Response. Use (response = > {/ / ------------------------------------------------------------------------------------------ removePending(res.config); // Cancel after an Ajax response, The request has completed removed from the pending / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - if(response.data.errCode ==2){ router.push({ path:"/login", Querry: {redirect: router. CurrentRoute. FullPath} / / from which page jump})} return response; }, error => { return Promise.reject(error) } )Copy the code
The reference link cancels the previous request, so the request has already been sent and still adds to the server’s burden. Cancelling an interface request can be interrupted either while the request is going out or while the response is coming back. At present, this can only ensure that the front-end data acquisition is normal.
So to prevent repeated clicking, you can make the button gray or loading.
In addition, the session can be marked at the time of execution by the server, and then unmarked at the end. The front end checks whether the mark exists according to this, and then sends the request if it does not exist.
Another solution:
Set a cancelFlag as the flag, which defaults to true. When requesting the interceptor, determine if cancelFlag is true, the request can be sent, and set cancelFlag to false. When cancelFlag is false, the request is cancelled. CancelFlag is set to true again in the response interceptor. Note Only after a request is sent and a response is received, another request can be sent. The problem here: cancelFlag is a global variable, so requests from multiple pages and interfaces can affect each other. The solution here is to build the constructor in axios.js, which allows cancelFlag to be privatized, but that will take up a lot of memory. Version 1 code:
import Vue from 'vue' import axios from 'axios' import {Indicator} from 'mint-ui' Vue.component(Indicator) let CancelToken = axios.CancelToken let cancelFlag = true Axios.defaults. headers = {' x-requested-with ': 'the XMLHttpRequest} axios. Defaults. Timeout = 20000 / / when the request interceptor axios. Interceptors. Request. Use (config = > {if (cancelFlag) { cancelFlag = false Indicator.open() } else { cancelToken: new CancelToken (c => { cancel = c }) cancel() } return config }, error => { return Promise.reject(error) }) axios.interceptors.response.use(config => { cancelFlag = true Indicator.close() return config }, error => { // })Copy the code
Version 2: With a requestName parameter for asynchronous requests. Request A will cancel axios[requestName] and AXIos [requestName].cancel if axios[requestName] and AXIos [requestName].cancel exist. Axios [requestName] and AXIos [requestName].cancel will still exist when the request is clicked. This will still execute axios[requestName].cancel(). This is because the axios[requestName].cancel method is invalid after the last request was successfully sent, and will not work even if it was executed. The value of axios[requestName].cancel is always the cancellation callback of the previous request. When the last request was successful, the callback is invalidated.
axios.interceptors.request.use(config => {
let requestName = config.data.requestName
if (requestName) {
if (axios[requestName] && axios[requestName].cancel) {
axios[requestName].cancel()
}
config.cancelToken = new CancelToken (c => {
axios[requestName] = {}
axios[requestName].cancel = c
})
}
return config
}, error => {
return Promise.reject(error)
})
Copy the code
Reference links:
Ajax: Async Javascript And Xml
Typically, requests and responses are sent from the browser to the server. AJAX is a browser feature. The browser adds an XMLHttpRequest function to the window. This constructor (class) can be used to construct an object through which the JS initiates the request and receives the response.
Sending requests using Ajax has four steps:
The first step is to create the XMLHttpRequest object, The second step is to use the object’s open method, which passes in the path of the request and the method. The third step is to listen for the object’s onReadyStatechange event and do that in the event handler. The fourth step is to use the object’s Send method.
var request = new XMLHttpRequest();
request.open(method,url);
request.onreadyStateChange = ()=>{};
request.send();
Copy the code
Cross domain (CORS,JSONP)
Browsers have same-origin policy restrictions. The same protocol, address, and port number are the same. This limitation causes that if a browser makes a request to the server, the request will be rejected if the address from which the request was made and the address to be requested are from a different source. Ajax requests are subject to this limitation, so how do you handle it? Generally, two methods are adopted, CORS and JSONP.
CORS is set on the server side, set the response header access-Control-allow-origin to add urls that Allow cross-domain Access. The specific documents are on MDN.
But Internet Explorer does not support CORS, so JSONP is used instead. JSONP has nothing to do with JSON, which is a markup language. JSONP makes use of the browser to request JS files without restrictions, using script tags with SRC attributes such as tags to initiate a request, request a JS file. The js file will execute a callback with the desired data. Normally, the name of the callback function is randomly generated and passed as a callback argument. JSONP is compatible with IE and can cross domains, but it only supports GET requests, not POST requests. And unlike Ajax, where you can get the status code returned by the request, JSONP only knows success or failure, not the response header.
Promise and use promises to encapsulate Ajax and JSONP
Ajax operations are asynchronous and cannot get results directly. The front end uses the Promise solution for asynchronous operations. It has the advantage of standardizing names, eliminating callback hell, and facilitating error handling.
New PROMISE ((resolve,reject)=>{async, resolve if successful; Failed reject; });
Promise objects have two characteristics: one is that the state of the object is not affected by the outside world; the other is that once the state changes, it will not change again. This result can be obtained at any time.
But it also has disadvantages. First, once a promise is set, it cannot be cancelled. Second, if you don’t set a callback function, errors thrown inside a Promise won’t be reflected externally. Third, when you are in a pending state, you have no way of knowing what stage of progress you are currently in (just beginning or just finishing). But axios can cancel, using the cancelToken method, not the promise, but the corresponding Ajax request. The Promise will still operate, but the corresponding Ajax request will be aborted, no more.
Here’s a simple Ajax request wrapped in promise:
function ajax(method,url){ return new Promise((resolve,reject)=>{ var request = new XMLHttpRequest(); request.open(method,url); Request. The onreadyStateChange = () = > {the if (request. ReadyState = = = 4) {/ / success will call resolve failure is invoked reject the if (request. The status < 400) { resolve.call(null,request.response); }else if(request.status>=400){ reject.call(null,request); }}}; request.send(); }); } ajax("get","/xxx").then((response)=>{},(request)=>{});Copy the code
Return new Promise((resolve,reject)=>{… }); Resolve (result) is called on success, reject(error) is called on failure, and resolve and Reject are called on success and failure. The second step uses. Then (success,fail) to pass in the success and failure functions. At present, encapsulation is relatively simple, can not post upload data, can not set the request header. This can be done using jquery. ajax or Axios.
Here is a simple JSONP request wrapped in a Promise:
function jsonp(url){ return new Promise((resolve,reject)=>{ let rannum = "ff"+Math.random(); window[rannum] = (res)=>{ resolve(res); } let scr = document.createElement("script"); scr.src = `${url}? callback=${rannum}`; scr.onload = ()=>{ scr.remove(); }; scr.onerror = (ee)=>{ reject(ee); }; document.body.appenChild(scr); }); } jsonp(url).then(succ => {console.log(" this is jsonp ", succ); }, fail => { console.log(fail); });Copy the code
Note that on the server side, the request is processed by receiving the function name passed by the callback, and the corresponding JS file executes the function callback to return the desired data.
jQuery.ajax()
Since ajax and JSONP wrapped with Promise above are rudimentary, jquery.Ajax () and Axios are already wrapped for us to use.
The jQuery ajax () :
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success: function() {},
error: function() {}
})
Copy the code
It is an encapsulation of native XHR and also supports JSONP. All Ajax requests sent by jQuery are internally implemented by calling the.ajax() function. It is usually not necessary to call this function directly; you can do this using several simple methods that are already wrapped, such as the.ajax() function. It is usually not necessary to call this function directly; you can do this using several simple methods that are already wrapped, such as the.ajax() function. There is usually no need to call this function directly, and you can use a few handy wrapped methods, such as.get() and.load(). If you need to use those unusual options,.load(). If you need to use those unusual options,.load(). If you need unusual options,.Ajax () is more flexible to use.
Example: Send the ID as data to the server, save some data to the server, and notify its users once it’s done. If the request fails, the user is alerted.
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Copy the code
LocalStorage etc.
LocalStorage: The storage device is stored locally and its size is generally limited to 5 to 10 MB. Use Windows. LocalStorage. The getItem (key) to obtain, use window. The localStorage. SetItem (key) to set up.
Cookie: A string sent from the server to the browser. The browser must save this Cookie (unless deleted by the user) and attach the Cookie to subsequent requests for the same secondary domain name (any request). Generally, the maximum is 4K.
Session: Based on cookies, the session ID is stored in the cookie.
Cookie and localstorage difference, one is size, two is cookie will be sent to the server, and localstorage will not.
The difference between a session and a cookie is that the session is stored in a server file and the cookie is stored in a browser file.
LocalStorage generally does not expire automatically (unless manually cleared by the user), whereas sessionStorage expires at the end of the session (such as closing the browser).
1. The closure
What is a closure, what is a closure’s purpose, and what are its disadvantages? Closure: A function that can read variables inside other functions. In JS, only subfunctions defined inside functions can read local variables, so a closure is understood as a function defined inside a function. Think of it as a bridge between the inside and outside of the function. [Use external variables] Purpose: Is to read the internal variables of the function, so that the value of the variable has been saved in memory. Hide local variables and expose operating functions:
const createAdd = ()=>{
let n = 0
return ()=>{
n += 1
console.log(n)
}
}
const add = createAdd()
add() // 1
add() // 2
Copy the code
Disadvantages: Because variables are always stored in memory, memory consumption will be large, resulting in poor web performance. So before exiting the function, remove all unused local variables. And because it can change the values of internal variables outside the parent function, it makes the data insecure. Easy to leak memory
function addAge(){
let age = 21;
return function(){
age++;
console.log(age);
}
}
const closure = addAge;
closure();
closure()();
Copy the code
Please understand the following two examples and also note this!!
var name = "windowname"; var obj1 = { name: "obj1name", getName: function(){ return function(){ return this.name; } } } alert(obj1.getName()()); //windownameCopy the code
///////////////////////////////////////////////////////////////
var name = "windowname"; var obj2 = { name: "obj2name", getName: function(){ var that = this; return function(){ return that.name; } } } alert(obj2.getName()()); //obj2nameCopy the code
The first of the two examples above, alert(obj1.getName()()), is executed in the context of the global execution, so this points to the Window object. In the second example, the object is passed as this to the anonymous callback inside, so it is called later, and when called, the call is the object’s name property.
2) Call apply bind
Bind, call, and apply are all used to change the direction of this. Take a look at the following example :(you can relate the two examples above)
let name = 'lucy' let obj = { name:'martin' say:function(){ console.log(this.name) } }; obj.say(); // Martin,this points to obj setTimeout(obj.say,0) // Lucy this points to windowCopy the code
We can get that normally this in say calls its obj object, and this in timer setTimeout points to the window object, This is because the SAY method is executed as a callback function in setTimeout and is therefore executed in the global execution context when back to the main stack. We need to specify the object to which this points.
The 1:call() method calls a function with a specified this value and one or more arguments given separately. function.call(thisArg, arg1, arg2, …) 1.1>thisArg optional. The this value used when function is run
1.2 > arg1, arg2,… Specifies the argument list
1.3> The return value is the return value from calling the function with the this value and arguments provided by the caller. If the method returns no value, undefined is returned.
1.4 example
var animal = "cat"; var obj1 = {animal:'cat1',food:'fish1'}; var obj2 = {animal:'cat2',food:'fish2'}; function greet(){ console.log(this.animal); }; greet.call(); // echo cat, equivalent to greet() greet.call(obj1); Cat1 greet.call(obj2); / / output cat2Copy the code
2: The apply() method calls a function with the given this value and the arguments supplied as an array (or array-like object). Func. Apply (thisArg, [argsArray]) :
2.1>thisarg is mandatory. Refers to the this value used when the func function is run.
2.2>argsArray is optional. Refers to an array or array-like object whose array elements are passed as separate arguments to the func function. If the parameter value is null or undefined, no parameters need to be passed in.
2.3> The return value is the result of calling the function with the specified this value and argument.
2.4 example
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
Copy the code
3: Bind () creates a new function. When bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments will be used as arguments to the new function when called. funcfunction.bind(thisArg[,arg1[,arg2[,…]]]); One of the simplest uses of bind() is to create a function that has the same value of this no matter how it is called.
this.x = 9; Var module = {x: 81, getX: function() {return this.x; }}; module.getX(); // 81 var retrieveX = module.getX; retrieveX(); // Return 9 - because the function is called in global scope // Create a new function, // A novice may confuse the global variable x with the module property x var boundGetX = retrievex.bind (module); boundGetX(); / / 81Copy the code
Bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind bind Call (x,y,z); call(x, y,z); call(x, y,z);
3. How to implement array deduplication
Array =[{name:’ WWW ‘},2]; array=[{name:’ WWW ‘},2]; You can also push the qualified results directly into the results.
function unique(arr){ let res = []; let hashdata = {}; for(let i=0; i<arr.length; i++){ hashdata[arr[i]] = true; } for(let k in hashdata){ res.push(k); } return res; } function unique(arr){ let res = []; for(let i=0; i<arr.length; i++){ if(res.indexOf(arr[i])===-1){ res.push(arr[i]); } else{ continue; } } return res; }Copy the code
2> The disadvantage of using SET is that the API is too new to be supported by older browsers
function unique(arr){
return [...new Set(arr)]
}
Copy the code
3> Using Map, the disadvantage is that the API is too new to be supported by older browsers
function unique(arr){ let map = new Map(); let result = []; for(let i=0; i<arr.length; i++){ if(map.has(arr[i])){ continue; }else{ map.set(arr[i],true); res.push(arr[i]); } } return res; }Copy the code
4. DOM event correlation
Event delegate: Also known as event delegate, it uses the principle of event bubbling to add events to parent or ancestor elements to trigger execution effects. That is, you can manage all events of a certain type by specifying a single event handler. Listen not on element A itself, but on its ancestor element B, and then determine if E.target is element A (or A child of the element).
The principle of event delegation: Event delegation is implemented using the bubbling principle of events. What is event bubbling? That is, events start at the deepest node and propagate up. For example, the page has a tree of nodes div>ul>li>a; For example, if we add a click event to the innermost div, the event will be executed layer by layer, in the order of A > Li >ul>div. There is a mechanism for adding a click event to the outermost div, and ul, Li, and a inside will do the click event. They all bubble up to the outermost div, so they all fire, and that’s the event delegate, delegating their parent to execute the event.
Advantages of event delegate: 1. Improves JS performance. Compared with event distribution (i.e. one DOM per event handler), event delegation can significantly improve event processing speed and reduce memory usage. 2. Dynamic DOM elements are added without changing event binding due to element changes
Event delegation also has some limitations. For example, events such as Focus blur have no event bubble mechanism, so they cannot be delegated. Events such as Mousemove Mouseout have bubbling events, but can only be computed and positioned by location, which is high in performance and therefore not suitable for event delegation.
Click MouseDown mouseUp KeyDown KeyUp KeyPress Of all mouse events, only mouseEnter Mouseleave does not bubble. All other mouse events bubble.
Prevent default action: [e.preventDefault() or return false]
function myfn(e){
window.event? window.event.returnValue=false :e.preventDefault();
}
Copy the code
【 e.topPropagation ()】
function myfn(e){
window.event? window.event.cancelBubble = true : e.stopPropagation();
}
Copy the code
5. Js inheritance
Prototype-based inheritance: [
function Parent(name1){
this.name1 = name1;
}
Parent.prototype.pmethod = ()=>{
console.log(this.name1);
}
function Child(name2,name1){
Parent.call(this,name1);
this.name2 = name2;
}
Child.prototype.__proto__ = Parent.prototype;
Child.prototype.cmethod = ()=>{
console.log(this.name2);
}
Copy the code
Class based inheritance: 【
class parent{ constructor(name1){ this.name1 = name1 } pmethod(){ console.log(this.name1); } } class child extends parent{ constructor(name2,name1){ super(name1); this.name2 = name2; } cmethod(){ console.log(this.name2); }}Copy the code
】
Reference soft teacher’s blog Javascript inheritance mechanism design ideas
function DOG(name){ this.name = name; } prototype = {new DOG("miaomiao"); var dog2 = new DOG("benben"); alert(dog1.species); / / canine alert (dog2. Species); // prototype = 'cat '; alert(dogA.species); / / the cat alert (dogB. Species); / / the catCopy the code
Since all instance objects share the same Prototype object, the Prototype object looks as if it is a prototype of the instance object, and the instance object looks as if it “inherits” the Prototype object.
Class DOG{species=" DOG "; constructor(name){this.name = name; } } var dog3 = new DOG("doudou"); alert(dog3.species); / / canine alert (dog3. Name); //doudouCopy the code
6. Sorting arrays
7) Understanding of Promise
0.Promise is the current unified solution for the front-end to solve asynchronous problems. A Promise can be understood as a container that holds the result of an event (usually the result of an asynchronous operation that will end in the future). A Promise is an object, the final completion (or failure) of an asynchronous operation, and its result value. It allows you to get messages for asynchronous operations, and it provides a unified API from which all kinds of asynchronous operations can be handled in the same way. The Promise solution addresses the problems that arise when addressing asynchronous programming problems, such as irregularities, prone to callback hell, and difficult error handling.
1. Create a Promise object:
Return new Promise((resolve,reject)=>{}) const promise1 = new Promise(function(resolve,reject){// Resolve (value); resolve(value); }else{ reject(error); }});Copy the code
2. Use promise.prototype.then (), which adds a callback to the Promise instance when the state changes. The first argument to the THEN method is the resolved state callback, and the second argument (optional) is the Rejected state callback. Using the then method, you still return a Promise object, but this is a new Promise object. So, we can use the chain notation. As a general rule, do not define a Reject callback (the second argument to a THEN) in a THEN method. Always use catch. The promise.prototype. catch method is used to specify the callback function when an error occurs. As written below, this has the advantage of catching errors in the execution of the previous THEN methods, and is closer to synchronous writing (try/catch). Also note that unlike traditional try/catch blocks, the error thrown by a Promise object is not passed to the outer code without a callback that uses the catch method to specify error handling.
Promise.prototype.then(function1(){}).catch(function2(){}); //Copy the code
3.Promise.all() is used to wrap multiple Promise instances into a new Promise instance. const p = Promise.all([p1, p2, p3]); In this code, the promise.all () method takes an array as an argument, and p1, P2, p3 are all Promise instances. If not, it is converted to an instance for further processing. In addition, the promise.all () method can take arguments that are not arrays, but must have an Iterator interface and return each member as a Promise instance. The state of P is determined by P1, P2 and P3, which can be divided into two cases. (1) Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P. (2) As long as p1, P2 and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function.
4.Promise.race() also wraps multiple promises into a new Promise instance. Unlike the All method, however, the state of the new Promise instance changes as long as one of the passed parameter instances changes state first. The return value of the first changed Promise instance is passed to the callback of the new Promise instance. The parameters of the promise.race () method are the same as those of the promise.all () method. If it is not a Promise instance, the promise.resolve () method, described below, is first called to turn the parameters into a Promise instance, and then further processing.
Promises are used to avoid callback regions and make the code look more synchronous.
Function fn(){return new Promise((resolve,reject)=>{resolve(data); Reject (reason) is called on failure; }); }Copy the code
How to use the Promise. Prototype. Then: fn (). Then (success, the fail). Then (success2, fail2). The catch (fail3) how to use Promise.all: promise. all([promise1,promise2]) parallel, waiting for all promises to succeed. If both succeed, the promise corresponding to all succeeds, and if one fails, the promise corresponding to all also fails. Promise.race: promise.all ([promise1,promise2]) returns a Promise that will be resolved or rejected if one of the promises in the array is resolved or rejected. 】
8 “across domains
Homologous: If the protocol, domain name, and port number of two urls are the same, the two urls are homologous. The same origin policy is a function that is deliberately designed by the browser for user privacy and data security. Pages from different sources cannot access each other’s data.
Cross-domain: Cross-domain means that data can be accessed between pages from different sources, breaking the same origin policy of the browser.
JSONP Cross-domain: Browsers do not support another cross-domain approach to CORS cross-domain. It takes advantage of the fact that browsers don’t limit references to JS, and we can reference JS at will. In this case, we request a JS file, which will perform a callback with the requested data. Because it’s a Script tag, you can’t listen for the return code like Ajax does, that is, you don’t know what the returned status code is, you don’t know what the response header is, just success or failure. Since it is a script tag, only GET requests can be sent. Post is not supported.
CORS Cross-domain: CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source. Its use is to set the response header to add the url that is allowed to access it.
9 “1 using Promise’s simple wrapper Ajax (Axios jquery.ajax) 2 Cross-domain asynchronous callback
function ajax(method,url){ return new Promise((resolve,reject)=>{ var request = new XMLHttpRequest(); request.open(method,url); Request. The onreadyStateChange = () = > {the if (request. ReadyState = = = 4) {/ / success will call resolve failure is invoked reject the if (request. The status < 400) { resolve.call(null,request.response); }else if(request.status>=400){ reject.call(null,request); }}}; request.send(); }); } ajax("get","/xxx").then((response)=>{},(request)=>{});Copy the code
Return new Promise((resolve,reject)=>{… }); Resolve (result) is called on success, reject(error) is called on failure, and resolve and Reject are called on success and failure. The second step uses. Then (success,fail) to pass in the success and failure functions.
At present, encapsulation is relatively simple, can not post upload data, can not set the request header. This can be done using jquery. ajax or Axios.
function jsonp(url){ return new Promise((resolve,reject)=>{ let rannum = "ff"+Math.random(); window[rannum] = (res)=>{ resolve(res); } let scr = document.createElement("script"); scr.src = `${url}? callback=${rannum}`; scr.onload = ()=>{ scr.remove(); }; scr.onerror = (ee)=>{ reject(ee); }; document.body.appenChild(scr); }); } jsonpp(url).then(succ => {console.log(" this is jsonp ", succ); }, fail => { console.log(fail); });Copy the code
Note that on the server side, the request is processed by receiving the function name passed by the callback, and the corresponding JS file executes the function callback to return the desired data.