Interface call mode
- Native ajax
- Jquery-based Ajax
- fetch
- axios
asynchronous
- JavaScript execution environment is “single threaded”
- The so-called single thread refers to that there is only one thread in the JS engine responsible for interpreting and executing JavaScript code, that is, only one task can be completed at a time, and the next task can be executed after the completion of this task, which will “block” other tasks. This task can be called the main thread
- Asynchronous mode can perform multiple tasks together
- JS common asynchronous calls
- Timing of any
- ajax
- Event functions
promise
- Mainly solve the problem of asynchronous deep nesting
- Promise provides a concise API to make asynchronous operations easier
<script type="text/javascript">
We use new to build a Promise. The constructor for a Promise takes one argument, which is the function, and passes in two arguments: Resolve and reject indicate the callback function */ after an asynchronous operation succeeds and */ after an asynchronous operation fails
var p = new Promise(function(resolve, reject){
//2. This is used to implement the asynchronous task setTimeout
setTimeout(function(){
var flag = false;
if(flag) {
//3. Normal condition
resolve('hello');
}else{
//4. Abnormal condition
reject('Wrong'); }},100);
});
// 5 After the Promise instance is generated, the then method can be used to specify the Resolved and REJECT callback functions
// In the THEN method, you can return the data directly instead of the Promise object, and receive the data in the later THEN
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});
</script>
Copy the code
Send Ajax requests based on promises
<script type="text/javascript">Var p = new Promise(function(resolve, resolve)); reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ! = 4) return; Resolve (xhr.responsetext); if(xhr.readyState == 4 &&xhr.status == 200) {# 1.2 resolve(xhr.responsetext); }else{# 1.3 reject(' server error '); }}; xhr.open('get', url); xhr.send(null); }); return p; } # In the then method, you can also return data directly instead of a Promise object, In the back of the then can receive data queryData (' http://localhost:3000/data '). Then (function (data) {the console. The log (data) # 1.4 want to continue the chain programming Need to be return return queryData('http://localhost:3000/data1'); }) .then(function(data){ console.log(data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data) });</script>
Copy the code
Promise the basic API
Instance methods
.then()
- Get correct results for asynchronous tasks
.catch()
- Obtaining exception Information
.finally()
- Success or failure (not formal criteria)
<script type="text/javascript">// / console.dir(Promise); function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } // foo() // .then(function(data){ // console.log(data) // }) // .catch(function(data){ // console.log(data) // }) // .finally(function(){ // console.log('finished') // }); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / two writing is the equivalent of foo (). Then (function (data) {# asynchronous tasks right results the console. The log (data)}, function (data) { Console.log (data)}) finally(function(){console.log('finished')});</script>
Copy the code
A static method
.all()
Promise.all
Method takes an array of objects (P1, P2, p3) that are instances of a Promise. (If it is not a Promise, the item will be used.Promise.resolve
Convert to a promise). Its state is determined by the three promise instances
.race()
Promise.race
The method also takes an array as an argument. When the state of one instance in P1, P2, p3 changes (becomesfulfilled
orrejected
), and the state of P changes accordingly. And pass the return value of the first promise that changed the state to p’s callback
<script type="text/javascript">
/* Promise uses API- object methods */
// console.dir(Promise)
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState ! =4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// Handle normal situations
resolve(xhr.responseText);
}else{
// Handle exceptions
reject('Server error'); }}; xhr.open('get', url);
xhr.send(null);
});
}
var p1 = queryData('http://localhost:3000/a1');
var p2 = queryData('http://localhost:3000/a2');
var p3 = queryData('http://localhost:3000/a3');
Promise.all([p1,p2,p3]).then(function(result){
// the parameters [p1,p2,p3] in all correspond to ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
})
Promise.race([p1,p2,p3]).then(function(result){
// Since p1 executes faster, Promise's then() will get the result 'p1'. P2,p3 continue to execute, but the execution results will be discarded.
console.log(result) // "HELLO TOM"
})
</script>
Copy the code
fetch
- The Fetch API is the new Ajax solution where Fetch returns promises
- Fetch is not a further encapsulation of Ajax, but rather native JS, without using XMLHttpRequest objects.
- The fetch (url, options). Then ()
<script type="text/javascript">
Fetch (url).then() The first parameter of the request path Fetch returns a Promise, so we can use then to get the result of a successful request */
fetch('http://localhost:3000/fdata').then(function(data){
The text() method, which is part of fetchAPI, returns a Promise instance object that gets the data returned in the background
return data.text();
}).then(function(data){
// In this then we can get the final data
console.log(data);
})
</script>
Copy the code
HTTP requests in the FETCH API
- The fetch (url, options). Then ()
- HTTP protocol, it provides us with many methods, such as POST, GET, DELETE, UPDATE, PATCH and PUT
- The default is a GET request
- You need to specify the corresponding method in the Options object. Method: The method used in the request
- For post and normal requests, you need to set headers and body in options
<script type="text/javascript">/* Fetch API calls interface pass parameter */ #1.1 GET parameter pass - traditional URL through URL? In the form of spread and the fetch (' http://localhost:3000/books? Id =123', {# get request can be omitted without writing the default is get method: 'get'}). Then (function(data) {# return data.text(); }). Then (function(data) {# console.log(data)}); # 1.2 the GET parameter passing in the form of a restful URL in the form of pass/passing parameters Id = 456 and configuration id the background about the fetch (' http://localhost:3000/books/456 ', }). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) }); Way # 2.1 the DELETE request parameter passing DELETE id is the id = 789 the fetch (' http://localhost:3000/books/789 '{method: 'delete' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # 3 POST request pass and the fetch (' http://localhost:3000/books' {method: "POST", # 3.1 pass data body: 'uname=lisi&pwd=123', # 3.2 Headers: {' content-type ': 'application/x-www-form-urlencoded' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # transmit and fetch POST request (' http://localhost:3000/books' {method: "POST", the body: JSON. Stringify ({uname: 'Joe Smith, PWD: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # transmit and modify the PUT request id is 123, fetch (' http://localhost:3000/books/123 '{method:' PUT 'body: JSON. The stringify ({uname: }}). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) });</script>
Copy the code
Format of the response in fetchAPI
- Fetch is used to obtain data. If the response is returned normally, the first thing we see is a Response object, which includes a bunch of returned original bytes. After receiving these bytes, we need to call methods to convert them into data in the corresponding format, such as
JSON
.BLOB
orTEXT
, etc.
/* Fetch the data format of the response result */
fetch('http://localhost:3000/json').then(function(data){
// return data.json(); // Convert the obtained data to an object using JSON
return data.text(); // // converts the obtained data to a string
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
Copy the code
axios
- HTTP client based on Promise for browsers and Node.js
- Supports browsers and Node.js
- Supporting promise
- Intercepts requests and responses
- Automatically convert JSON data
- Ability to transform request and response data
Basic usage of axios
- Get and DELETE requests pass parameters
- Through the traditional URL with? Pass parameters in the form of
- Restful pass parameters
- Pass parameters through params
- Post and PUT requests pass parameters
- Pass parameters through options
- Pass parameters through URLSearchParams
# 1.Send the get request axios.get('http://localhost:3000/adata').then(function(ret){# get ret is an object. All objects are stored in ret's data property// Note that the data attribute is a fixed use to get the actual data in the background
// console.log(ret.data)
console.log(ret)
})
# 2.Get requests pass parameter #2.1Through the traditional URL with? Pass the argument axios.get('http://localhost:3000/axios? id=123').then(function(ret){
console.log(ret.data)
})
# 2.2Pass the argument axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
# 2.3Pass the argument axios.get(params)'http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
#3 axios deleteRequest parameters are passed in the same form as get requests axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
# 4Axios post request #4.1Pass the argument axios.post('http://localhost:3000/axios', {
uname: 'lisi'.pwd: 123
}).then(function(ret){
console.log(ret.data)
})
# 4.2Pass parameters through URLSearchParamsvar params = new URLSearchParams();
params.append('uname'.'zhangsan');
params.append('pwd'.'111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
#5Axios put A request to pass parameters is the same as a POST request.'http://localhost:3000/axios/123', {
uname: 'lisi'.pwd: 123
}).then(function(ret){
console.log(ret.data)
})
Copy the code
Axios global configuration
Configure the common request header axios.defaults.baseURL ='https://api.example.com'; Axios.defaults. timeout =2500; # configuration of public request header mon [axios.defaults.headers.com'Authorization'] = AUTH_TOKEN; # configuration of public post the content-type axios. Defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded';
Copy the code
Axios interceptor
- Request interceptor
- The purpose of a request interceptor is to do something before a request is sent
- For example, add token to each request body, which makes it easy to change later
- The purpose of a request interceptor is to do something before a request is sent
- Response interceptor
- The purpose of a response interceptor is to do something after receiving a response
- For example, if the server login status is invalid and you need to log in to the server again, the login page is displayed
- The purpose of a response interceptor is to do something after receiving a response
# 1.Request interceptor axios. Interceptors. Request. Use (function(config) {
console.log(config.url)
# 1.1Any request will go through this step and do something before sending the request config.headers. Mytoken ='nihao';
# 1.2You have to make surereturnOtherwise, the configuration failsreturn config;
}, function(err){#1.3What to do about the request errorconsole.log(err)
})
#2.Response interceptor axios. Interceptors. Response. Use (function(res) {#2.1What do YOU do when you receive a responsevar data = res.data;
return data;
}, function(err){#2.2What do you do about the response errorconsole.log(err)
})
Copy the code
Async and await
- Async precedes functions as a keyword
- Any one
async
All functions implicitly return onepromise
- Any one
await
The keyword can only be usedasync
Used in a function defined by- Await can be followed directly by a Promise instance object
- The await function cannot be used alone
- Async /await makes asynchronous code look and behave more like synchronous code
# 1. asyncBasic usage #1.1 asyncPut it in front of the function as a keywordasync function queryData() {#1.2 awaitThe keyword can only be usedasyncUsed in a function defined byawaitYou can just follow one of themPromiseInstance objectsvar ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')},1000);
})
// console.log(ret.data)
return ret;
}
# 1.3Any oneasyncAll functions implicitly return a promise and we can chain program with then queryData().then(function(data){
console.log(data)
})
#2. asyncFunction to handle multiple asynchronous functions axios.defaults.baseURL ='http://localhost:3000';
async function queryData() {#2.1addawaitAfter currentawaitThe following code is executed after the result is returnedvar info = await axios.get('async1');
#2.2Make asynchronous code look and behave more like synchronous codevar ret = await axios.get('async2? info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})
Copy the code
The Book List case
1. Interface-based case – Get book list
- Import AXIOS to send ajax
- Render the obtained data onto the page
<div id="app">
<div class="grid">
<table>
<thead>
<tr>
<th>Serial number</th>
<th>The name of the</th>
<th>time</th>
<th>operation</th>
</tr>
</thead>
<tbody>
<! -- 5. Render data from Books to page -->
<tr :key='item.id' v-for='item in books'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date }}</td>
<td>
<a href="">Modify the</a>
<span>|</span>
<a href="">delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>1. Import axios<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">/* library - add books */ # 2 configure the public URL address to simplify the following call method axios.defaults.baseURL = 'http://localhost:3000/'; axios.interceptors.response.use(function(res) { return res.data; }, function(error) { console.log(error) }); var vm = new Vue({ el: '#app', data: { flag: false, submitFlag: false, id: '', name: '', books: [] }, methods: {# 3 define a method to send Ajax # 3.1 Use async to make asynchronous code write queryData synchronously: Async function() {var ret = await axios.get('books'); // this.books = ret.data; Get ('books'); this.books = await axios.get('books'); }}, mounted: function() {# 5 mounted: function() {this.queryData(); }});</script>
Copy the code
2 Adding books
- Get the data entered by the user and send it to the background
- Render the latest data to the page
methods: {
handle: async function(){
if(this.flag) {
// Edit the book
// Update the array based on the current ID
this.books.some((item) = > {
if(item.id == this.id) {
item.name = this.name;
// After the update operation is complete, the loop needs to be terminated
return true; }});this.flag = false;
}else{#1.1Send the Ajax request # in the previously wrapped Handle method1.2useasync 和 awaitSimplifying operations needs to be done infunctionAdd in front of theasync
var ret = await axios.post('books', {
name: this.name
}) # 1.3 Determine whether to load data according to the status code returned in the backgroundif(ret.status == 200) {#1.4Call the queryData method to render the latest datathis.queryData(); }}// Clear the form
this.id = ' ';
this.name = ' '; }},Copy the code
3 Verify that the book name exists
- Send a request to verify that the schema already exists before adding the book
- If not, add the book name to the background
- You only need to change the value of submitFlag to check whether the book exists
watch: {
name: async function(val) {
// Verify that the book name already exists
// var flag = this.books.some(function(item){
// return item.name == val;
// });
var ret = await axios.get('/books/book/' + this.name);
if(ret.status == 1) {
// The book name exists
this.submitFlag = true;
}else{
// The book name does not exist
this.submitFlag = false; }}},Copy the code
4. Edit books
- Query the book that you want to edit based on the current book ID
- You need to determine whether to add or edit based on the status bits
methods: {
handle: async function(){
if(this.flag) {
#4.3Edit books and submit user input information to the backgroundvar ret = await axios.put('books/' + this.id, {
name: this.name
});
if(ret.status == 200){
#4.4Reload the list data after addingthis.queryData();
}
this.flag = false;
}else{
// Add books
var ret = await axios.post('books', {
name: this.name
})
if(ret.status == 200) {
// Reload the list data
this.queryData(); }}// Clear the form
this.id = ' ';
this.name = ' ';
},
toEdit: async function(id){#4.1The flag status bit is used to distinguish between editing and adding operationsthis.flag = true;
#4.2Query the latest information that can be loaded out of the corresponding book information page according to the IDvar ret = await axios.get('books/' + id);
this.id = ret.id;
this.name = ret.name;
},
Copy the code
5 Deleting books
- The id books to be deleted are passed to the background in the form of parameters
deleteBook: async function(id){
// Delete the book
var ret = await axios.delete('books/' + id);
if(ret.status == 200) {
// Reload the list data
this.queryData(); }}Copy the code