Basic use of Promise
Basic use
new promise, pass a function as a parameter for it. Two parameters are passed in this function, which are used to execute callback functions that succeed and fail asynchronous tasks.
function query(){ var p=new Promise(function(resolve,reject){ setTimeout(function(){ var flag=true; if(flag){ resolve('Right'); } else{ reject('Wrong'); } },1000) }); return p; } query().then(function(data){ //The first function receives the successful value (data); },function(data){ //The second function receives the failed value (data); }); Output result:‘By the way'
Multiple requests, chain programming
When we send multiple requests, traditional ajax will have multiple nested callback hell, and Promise provides us with chain programming.
function queryData(url) { var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); = function(){ if( != 4) return; if( == 4 && == 200) { // Handle normal situations resolve(); }else{ // Handle exceptions reject('Server Error'); } }; ('get', url); (null); }); return p; } // Send multiple ajax requests and ensure execution order queryData('http://localhost:3000/data') .then(function(data){ (data) //If you want to continue programming in chain, you must return return queryData('http://localhost:3000/data1'); }) .then(function(data){ (data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ (data) });
Promise API—Instance Method
-
.then()
: When two parameters are passed, only successful execution. When a parameter is passed, that parameter executes a successful callback. - Get successful results
-
.catch()
: When two parameters are passed, only the wrong ones are executed. When a parameter is passed, that parameter executes a failed callback. - Get exceptional results
-
.finally()
Not a formal standard - Will be executed regardless of success or not
<script type="text/javascript"> /* Promise Common API-Instance Method */ // (Promise); function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } foo() .then(function(data){ (data) }) .catch(function(data){ (data) }) .finally(function(){ ('finished') }); // -------------------------- // The two writing methods are equivalent foo() .then(function(data){ # Get the correct result of asynchronous tasks (data) },function(data){ # Get exception information (data) }) # Will be implemented whether it is successful or not (not the formal standard) .finally(function(){ ('finished') }); </script>
Promise API—Object method (method called directly through the Promise function name)
(1) () Concurrently process multiple asynchronous tasks, and all tasks are executed and completed before they can get the result.
-
The method accepts an array as a parameter, and the objects (p1, p2, p3) in the array are all promise instances (if it is not a promise, the item will be converted to a promise). Its status is determined by these three promise instances
(2) () Concurrently handle multiple asynchronous tasks, and as long as one task is completed, you can get the result.
-
The method also accepts an array as an argument. When the state of an instance in p1, p2, and p3 changes (changed into fulfilled or rejected), the state of p changes. And pass the return value of the first change state promise to the callback function of p
<script type="text/javascript"> /* Promise commonly used API-object methods */ // (Promise) function queryData(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); = function(){ if( != 4) return; if( == 4 && == 200) { // Handle normal situations resolve(); }else{ // Handle exceptions reject('Server Error'); } }; ('get', url); (null); }); } var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); ([p1,p2,p3]).then(function(result){ //The request time is related to the order of sending, send first, return first. // The parameters in all [p1,p2,p3] and the returned result are one and one corresponding to ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] (result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"] }) ([p1,p2,p3]).then(function(result){ // Since p1 executes faster, then() of Promise will get the result 'P1'. p2 and p3 are still executing, but the execution result will be discarded. (result) // "HELLO TOM" }) </script>
Interface call-fetch usage
Basic use
- Simpler data acquisition method, high performance, more powerful and flexible, can be regarded as an upgraded version of xhr
- Implementation of Promise
- Fetch API is the new ajax solution Fetch will return Promise
- fetch is not a further encapsulation of ajax, but native js, and does not use XMLHttpRequest object.
fetch(url, options).then() <script type="text/javascript"> /* Basic usage of Fetch API fetch(url).then() The path to the first parameter request Fetch will return Promise So we can use then to get the result of the successful request */ fetch('http://localhost:3000/fdata').then(function(data){ // The text() method belongs to part of the fetchAPI. It returns a Promise instance object to obtain the data returned by the background return (); //text() is an API of fetch, returning a Promise object }).then(function(data){ // In this then we can get the final data (data); }) </script>
Common configuration options
- fetch(url, options).then()
- HTTP protocol, it provides us with many methods, such as POST, GET, DELETE, UPDATE, PATCH and PUT
- The default is GET request
- You need to specify the corresponding method method in the options object: the method used by the request
- When post and normal requests, you need to set the request headers and body in options
GET Request
Traditional url request to pass parameters—pass parameters through "?"
Front-end code
fetch('http://localhost:3000/books?id=123', { # get request can be omitted without writing. The default is GET method: 'get' }) .then(function(data) { # It returns a Promise instance object to get the data returned by the background return (); }).then(function(data) { # In this then we can get the final data (data) });
Backend code
('/books'()=>{ ("Traditional url pass parameters"+); })
Restful form url pass parameters—pass parameters through "/"
Front-end code
fetch('http://localhost:3000/books/456', { # get request can be omitted without writing. The default is GET method: 'get' }) .then(function(data) { return (); }).then(function(data) { (data) });
Backend code
('/book/:id',()=>{ ("Restful format pass parameters"+); })
DELETE request
Similar to GET method, just change the method attribute to "delete"
Parameter passing of POST request method
When passing parameters on post, in addition to the method attribute, additional headers and body attributes are needed in the option object.
Front-end code
body is query string format
var url='http://127.0.0.1:3000/product/books/'; fetch(url,{ method:'post', headers:{ 'Content-Type':'application/x-www-form-urlencoded' }, body:'uname=Gao Jinyu&pwd=11223344' }).then(data=>{ return (); }).then(data=>{ (data); })
Backend code
('/books', (req, res) => { ('axios post pass parameters' + + '---' + ) })
Body is in JSON format
fetch('http://localhost:3000/books', { method: 'post', body: ({ uname: 'Zhang San', pwd: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return (); }).then(function(data) { (data) });
Backend code
('/books', (req, res) => { ('axios post pass parameters' + + '---' + ) })
Parameter passing in PUT request mode
fetch response result
Use fetch to get data. If the response returns normally, the first thing we see is a response object, which includes a bunch of original bytes returned. After receiving these bytes, we need to convert them into data in the corresponding format by calling methods, such as JSON, BLOB, or TEXT, etc.
-
text()
: Process the return body into a string -
json()
: The return result is the same as ()
/* Data format of Fetch response result */ fetch('http://localhost:3000/json').then(function(data){ // return (); // Use json to convert the obtained data to convert the object return (); // // Convert the obtained data into a string }).then(function(data){ // () // (typeof data) var obj = (data); (,,) })
Interface call – Axios usage
know
- Promise-based http client for browser and
- Supports browser and
- Support promise
- Ability to intercept requests and responses
- Automatically convert JSON data
- Ability to convert request and response data
Basic usage of axios
Common APIs of axios
get()
post()
delete()
put()
axios global configuration
Configure public request headers
= '';
Configure timeout
= 2500;
Configure public request headers
['Authorization'] = AUTH_TOKEN;
Configure the Content-Type of the public post
['Content-Type'] = 'application/x-www-form-urlencoded';
GET Request
Send a get request
('http://localhost:3000/adata').then(function(ret){ # Get ret is an object All objects exist in the data attribute of ret // Note that the data attribute is a fixed usage, which is used to obtain the actual data in the background () (ret) })
get request to pass parameters
Pass parameters in the form of ? through traditional url
('http://localhost:3000/axios?id=123').then(function(ret){ () })
Restful pass parameters
('http://localhost:3000/axios/123').then(function(ret){ () })
Pass parameters through params
Front-end code
('http://localhost:3000/axios', { params: { id: 789 } }).then(function(ret){ () })
Backend code
('/axios', (req, res) => { ('axios get passes parameters' + ) })
DELETE request to pass parameters
The parameter transfer form is the same as the GET request
POST request
Pass parameters through options (the default is json format data)
Front-end code
('http://localhost:3000/axios', { uname: 'lisi', pwd: 123 }).then(function(ret){ () })
Backend code
('/axios', (req, res) => { ('axios post pass parameters' + + '---' + ) })
Pass parameters through URLSearchParams (application/x-www-form-urlencoded)
var params = new URLSearchParams(); ('uname', 'zhangsan'); ('pwd', '111'); ('http://localhost:3000/axios', params).then(function(ret){ () })
PUT Request
Same as post request.
Axios' response results
-
data
: The actual response data. -
headers
: Response header information. -
status
: Response status code. -
statusText
: Response status information.
axios interceptor
Request Interceptor
The purpose of the request interceptor is to perform some operations before the request is sent.
For example, adding tokens to each request body will be done uniformly and it will be very easy to modify in the future.
(function(config) { () # 1.1 Any request will go through this step What to do before sending the request = 'nihao'; # 1.2 It is necessary to return here otherwise the configuration will not be successful return config; }, function(err){ #1.3 Do something to request error (err) })
Response Interceptor
The function of the response interceptor is to perform some operations after receiving the response.
For example, when the server returns to the login status and needs to log in again, jump to the login page
(function(res) { #2.1 What to do when receiving a response var data = ; return data; }, function(err){ #2.2 What to do with response errors (err) })
After the above response interceptor processing. The res obtained below are the data required and no more operations are required.
('http://localhost:3000/axios', { uname: 'lisi', pwd: 123 }).then(function(res){ (res) })
async and await
async as a keyword before the function
Any async function will implicitly return a promise
Await keyword can only be used in functions defined using async
- A Promise instance object can be directly followed by await
- Await function cannot be used alone
async/await makes the asynchronous code look and behave more like synchronous code
async/await is a new syntax introduced by ES7, which can be more convenient for asynchronous operations.
The async keyword is used on a function (the return value of the async function is a Promise object).
The await keyword is used in async functions (await can directly obtain asynchronous results).
Basic usage of async
//Async is placed in front of the function as a keyword async function queryData() { //The keyword await can only be used in functions defined using async Await can be directly followed by a Promise instance object var ret = await new Promise(function(resolve, reject){ setTimeout(function(){ resolve('nihao') },1000); }) // () return ret; } //Any async function will implicitly return a promise We can use then for chain programming queryData().then(function(data){ (data) })
The async function handles multiple asynchronous functions
= 'http://localhost:3000'; async function queryData() { // After adding await, the following code will be executed only after the current await returns the result. var info = await ('async1'); // Make asynchronous code look and behave more like synchronous code var ret = await ('async2?info=' + ); return ; } queryData().then(function(data){ (data) })
The above is personal experience. I hope you can give you a reference and I hope you can support me more.