[Promise] and [axios] of front-end learning development

0. supplement

1. Instance object and function object

Instance object : the object generated by the new function;
function object : use the function as an object; (operating attributes or methods)

2. Callback function

Defined by yourself, but not called by yourself, it will still be executed.
Synchronous callback :
Execute immediately, and it will not end until it is fully executed. will not be placed in the queue.
Asynchronous callback :
Put it in the queue for future execution. Don't do it directly at the beginning, execute it directly after startup, and then execute the callback function.

3. Error handling

Error type :

  • ReferenceError: reference variable does not exist;
  • TypeError: The data type is incorrect; (the type does not exist xxx property or method)
  • RangeError: out of range, infinite loop;
  • SyntaxError: syntax error.

Error handling :

  • Capture error: try catch capture error.message, stack
  • Throw an error: throw new Error(' ')

Error object :
message attribute: error related information;
stack attribute: function call stack record information.

1 Overview

1 Introduction

Asynchronous programming :

  • file operation
  • database operation
  • timer

Implementing Asynchronous Programming : Callback Functions

What are Promises?
Promise is a solution for asynchronous programming in JS. Syntactically speaking, it is a constructor. Functionally speaking, a promise object is used to encapsulate an asynchronous operation and obtain the result value of its success or failure.

Promise is a class provided by ECMAScript 6 to write complex asynchronous tasks more elegantly.

Why use Promise :

  1. Specify the callback function, which is more flexible: start the asynchronous task—return the promise object—bind the callback function to the promise object; in the past, the callback function must be prepared before starting the asynchronous task;
  2. Support chain calls to solve the problem of callback hell (continuous advancement, always nesting).

2. Promise state

  1. pending becomes resolved
  2. pending 变 rejected
  • Promise has only these two states, and an object can only be changed once;
  • Regardless of success or failure, there is only one result data;
  • The result of success is value, and the result of failure is reason.

Process :
insert image description here

3. Use the Promise process

Promise is a constructor that can instantiate an object. The parameter it receives is a value of function type. This function has two formal parameters, resolve and reject (also data of function type). Reslove is called successfully, and reject is called when it fails.

const p=new Promise((resolve,reject)=>{
    
    
//执行器函数 执行异步操作任务
//成功则调用resolve(value),将promise对象的状态设置为成功
//失败调用reject(reason),将promise对象的状态设置为失败
})

then method:
Receives two parameters, both of which are values ​​of function type. If it succeeds, the first callback function is executed, and if it fails, the second callback function is executed.

p.then(()=>{
    
    },()=>{
    
    })

4. Use util.pormisify(original) package

Pass in an error-first callback function (that is, take (err,value)=>{}a callback as the last argument), and return a promise version.
The Node.js built-in util module has a promisify() method that converts a callback-based function into a Promise-based function. This allows you to use Promise chains and async/await with callback-based APIs.

//引入util模块
const util=require('util');
//引入fs模块
const fs=require('fs');
//返回一个新函数
let mineReadFile=util.promisify(fs.readFile);
mineReadFile('./resource/content.txt').then(value=>{
    
    });

5. Encapsulate AJAX request

function sendAJAX(url){
    
    
	return new Promise((resolve,reject)=>{
    
    
	const xhr=new XMLHttpRequest();
	xhr.open("GET",url);
	xhr.send();
	xhr.onreadystatechange=function(){
    
    
		if(xhr.readystate===4){
    
    
			if(xhr.status>=200&&xhr.status<300)
			{
    
    
				resolve(xhr.response);
			}else{
    
    
				reject(xhr.status);
			}
		}
	}
}

sendAJAX('http://api')
.then(value=>{
    
    },reason=>{
    
    })

2. Theory

1. Promise state

A property PromiseState in the instance object

  • pending undecided
  • resolved, fullfilled successfully
  • rejected failed

A promise object can only be changed once, and there is only one data result, the success data is value, and the failure data is reason.

2. The value of the Promise object

Another attribute PromiseResult in the instance object
holds the result of the object's success or failure.
Function to modify the value:

  • resolve;
  • reject。

Then call the then method to perform related operations on the value.

3. API

Pay attention to see whether it belongs to a function object or an instance object.
insert image description here
insert image description here
insert image description here
resolve :
If the incoming parameter is a non-Promise object, the returned result is a successful promise object; if the incoming parameter is a promise object, the result of the parameter is the result of resolve.
If it fails, you need to catch it with catch.
insert image description here
insert image description here

4. Key Questions

How to change promise state :

  • Call the resolve function or reject function;
  • throw ' 'throws an error.

A promise specifies multiple callbacks, will they all be called :

  • Called when the promise changes to the corresponding state.

The order of changing the promise state and specifying the callback function :

  • It is possible, under normal circumstances, first specify the callback (then) and then change the state;
  • How to change the state first and then specify the callback: directly call resolve or reject in the executor; delay calling then;
  • When to get the data: If the callback is specified first, when the state changes, the callback function will be called to get the data; if the state is changed first, the callback will be called to get the data when the callback is specified.

then returns the resulting state of the promise object :

  • Determined by the execution result of the callback function specified by then();
    insert image description here
    insert image description here

Exception penetration :
If an exception is thrown before, it can be caught at the end, and then can be called in the middle.
insert image description here

3. Custom Promise

use:

let p=new Promise((resolve,reject)=>{
    
    
	resolve('ok');
});
p.then(value=>{
    
    },reason=>{
    
    });

customize:

  1. Define the overall structure: the constructor contains the executor parameter (function type), and the then function is added to the prototype chain; the reject and resolve functions are declared in the constructor, and the executor is called, and the parameters are reject and resolve;
  2. Set the reject and resolve functions: first add the properties PromiseState and PromiseResult and set the initial value; then save the instance object this, and then modify the variables in the two functions (note that the function has the formal parameter data as the result value);
  3. throw throws an exception: use try catch to catch the exception when calling the executor, and call reject;
  4. Setting the Promise state can only be modified once: set the judgment in the reject and resolve functions, if the state is not pending, return directly without modification;
  5. The then method executes the callback: the then method has two formal parameters of function type onResolved and onRejected, and the former is called when the state is fulfilled (the formal parameter is the result value);
  6. Execution of asynchronous task callback: In order to be able to specify a callback when the state has not changed, it is necessary to make a pending judgment in then, add a callback variable, and save the two callback functions onRejected and onResolved; add a call callback to the resolve and reject of the constructor;
  7. Specify the implementation of multiple callbacks: the callback is changed to an array, and multiple objects can be pushed, each object contains an onResolved and an onRejected; modify and call each callback in the resolve and reject functions;
  8. Synchronous task modification status then method result return: the return result of then is determined by the execution result of the callback function. Modify the then function and return the newly created Promise object. If the result is a promise, return the result of the then call. If it is not a promise object, then Call resolve to return;
  9. Asynchronous task modification state then method result return: add pending judgment to the above;
  10. Then method optimization: encapsulation hen的返回结果由回调函数的执行结果来决定,修改then函数,返回新建的Promise对象,如果结果是promise,则返回其then调用结果,如果不是promise对象,则调用resolve返回;
  11. catch method (exception penetration and value transfer):
  12. Encapsulate resolve, reject, all, race functions;
  13. The then method callback function is executed asynchronously: add a timer;
  14. Encapsulated into a class:
function Promise(executor){
    
    
	//添加属性
	this.PromiseState='pending';
	this.PromiseResult=null;
	this.callbacks={
    
    };
	//保存实例对象的this值
	const self=this;
	function resolve(data){
    
    
		if(self.PromiseState !=='pending')return;
		//1.修改对象状态(promiseState)
		self.PromiseState='fulfilled';
		//2.设置对象结果值(promiseResult)
		self.PromiseResult=data;
		setTimeout(()=>{
    
    
			self.callbacks.forEach(item=>{
    
    
				item.onResolved(data);
			})
		})
	}
	function reject(data){
    
    
		if(self.PromiseState !=='pending')return;
		//1.修改对象状态(promiseState)
		self.PromiseState='rejected';
		//2.设置对象结果值(promiseResult)
		self.PromiseResult=data;
		setTimeout(()=>{
    
    
			self.callbacks.forEach(item=>{
    
    
				item.onRejected(data);
			})
		})
		
	}
	try{
    
    
		//同步调用执行器函数
		excutor(resolve,reject);
	}catch(e){
    
    
		reject(e);
	}
	
}
//形参为函数
Promise.prototype.then=function(onResolved,onRejected){
    
    
	const self=this;
	if(typeof onRejected !=='function'){
    
    
		onRejected=reason=>{
    
    
			throw reason;
		}
	}
	if(typeof onResolved!=='function'){
    
    
		onResolved=value=>value;
	}
	return new Promise((resolve,reject)=>{
    
    
		//封装函数
		function callback(type){
    
    
			try{
    
    
				let result=type(this.PromiseResult);
				if(result istanceof Promise){
    
    
					result.then(v=>{
    
    
						resolve(v);
					},r=>{
    
    
						reject(r);
					})
				}else{
    
    
					resolve(result);
				}
			}catch(e){
    
    
				reject(e);
			}
		}
		//调用回调函数
		if(this.PromiseState==='fulfilled'){
    
    
			setTimeout(()=>{
    
    
				callback(onResolved);
			})
		}
		if(this.PromiseState==='rejected'){
    
    
			setTimeout(()=>{
    
    
				callback(onRejected);
			})
			
		}
		if(this.PromiseState==='pending'){
    
    
			//保存回调函数
			this.callbacks.push{
    
    
				onResolved:function(){
    
    
					callback(onResolved);
				},
				onRejected:function(){
    
    
					callback(onRejected);
				}
			}
		}
	})
}
Promise.prototype.catch=function(onRejected){
    
    
	return this.then(ondefined,onRejected);
}

Promise.resolve=function(value){
    
    
	return new Promise((resolve,reject)=>{
    
    
		if(value instanceof Promise){
    
    
			value.then(v=>{
    
    
				resolve(v)
			},r=>{
    
    
				reject(r);
			}
		}else{
    
    
			resolve(value);
		}
	}
}
Promise.reject=function(reason){
    
    
	return new Promise((resolve,reject)=>{
    
    
		reject(reason);
	}
}
Promise.all=function(promises){
    
    
	return new Promise((resolve,reject)=>{
    
    
		let count=0;
		let arr=[];
		for(let i=0;i<promises.length;i++){
    
    
			promises[i].then(v=>{
    
    
				count++;
				arr[i]=v;
				if(count===promises.length){
    
    
					resolve(arr);
				}
			},r=>{
    
    
				reject(r);
			})
		}
	}
}
Promise.race=function(promises){
    
    
	return new Promise((resolve,reject)=>{
    
    
		for(let i=0;i<promises.length;i++){
    
    
			promises[i].then(v=>{
    
    
				resolve(v);
			},r=>{
    
    
				reject(r);
			})
		}
	}
}
class Promise{
    
    
	constructor(executor){
    
    
			//添加属性
	this.PromiseState='pending';
	this.PromiseResult=null;
	this.callbacks={
    
    };
	//保存实例对象的this值
	const self=this;
	function resolve(data){
    
    
		if(self.PromiseState !=='pending')return;
		//1.修改对象状态(promiseState)
		self.PromiseState='fulfilled';
		//2.设置对象结果值(promiseResult)
		self.PromiseResult=data;
		setTimeout(()=>{
    
    
			self.callbacks.forEach(item=>{
    
    
				item.onResolved(data);
			})
		})
	}
	function reject(data){
    
    
		if(self.PromiseState !=='pending')return;
		//1.修改对象状态(promiseState)
		self.PromiseState='rejected';
		//2.设置对象结果值(promiseResult)
		self.PromiseResult=data;
		setTimeout(()=>{
    
    
			self.callbacks.forEach(item=>{
    
    
				item.onRejected(data);
			})
		})
		
	}
	try{
    
    
		//同步调用执行器函数
		excutor(resolve,reject);
	}catch(e){
    
    
		reject(e);
	}
	}
	then((onResolved,onRejected){
    
    
	const self=this;
	if(typeof onRejected !=='function'){
    
    
		onRejected=reason=>{
    
    
			throw reason;
		}
	}
	if(typeof onResolved!=='function'){
    
    
		onResolved=value=>value;
	}
	return new Promise((resolve,reject)=>{
    
    
		//封装函数
		function callback(type){
    
    
			try{
    
    
				let result=type(this.PromiseResult);
				if(result istanceof Promise){
    
    
					result.then(v=>{
    
    
						resolve(v);
					},r=>{
    
    
						reject(r);
					})
				}else{
    
    
					resolve(result);
				}
			}catch(e){
    
    
				reject(e);
			}
		}
		//调用回调函数
		if(this.PromiseState==='fulfilled'){
    
    
			setTimeout(()=>{
    
    
				callback(onResolved);
			})
		}
		if(this.PromiseState==='rejected'){
    
    
			setTimeout(()=>{
    
    
				callback(onRejected);
			})
			
		}
		if(this.PromiseState==='pending'){
    
    
			//保存回调函数
			this.callbacks.push{
    
    
				onResolved:function(){
    
    
					callback(onResolved);
				},
				onRejected:function(){
    
    
					callback(onRejected);
				}
			}
		}
	})
}

	catch(onRejected){
    
    
		return this.then(ondefined,onRejected);
	}

	static resolve(value){
    
    }
	static reject(reason){
    
    }
	static all(promises){
    
    }
	static race(promises){
    
    }
}

4. async and await

1. async function

  • The return value is a promise object;
  • The result of the promise object is determined by the return value of the async function execution: if the return value is a non-promise object, the result is a promise object in a successful state, and the result value is the return value; if the returned result is a promise object, the object is returned ; If an exception is thrown, returns a failed promise with the result value being the thrown value.

2. await expression

  • The expression on the right side of await is generally a promise object, and it can also be other values;

  • If the expression is a promise object, await returns the result value of the promise success;

  • If the right side is a failed promise object, it must be captured by try catch to get the failed result;

  • If the expression is another value, directly use this value as the return value of await.

  • await must be written in the async function, but there can be no await in the async function;

  • If the promise of await fails, an exception will be thrown, which needs to be caught and processed by try catch.

3. Combination of async and await

  1. Error handling and callback are more convenient: direct try catch;
  2. When sending ajax, call the encapsulated function directly.

5.axios

1 Introduction

Axios is a promise-based encapsulation of ajax. Axios is a promise-based network request library for node.js and the browser. It is isomorphic (ie the same code can run in the browser and node.js). On the server side it uses the native node.js http module, and on the client side (browser side) it uses XMLHttpRequests.

mvvm:
insert image description here

2. Basic use

By default, the get method is used to send a request without parameters :

axios({
    
    
	url:'https://api'
}).then(res=>{
    
    })

Specify the get method to send a request without parameters :

axios({
    
    
	url:'https://api'method:'get'
}).then(res=>{
    
    })

Specify the post method to send a request without parameters :

axios({
    
    
	url:'https://api'method:'post'
}).then(res=>{
    
    })

get sends a request with parameters :

axios({
    
    
	url:'https://api?key=value',
	method:'get'
}).then(res=>{
    
    })
axios({
    
    
	url:'https://api',
	params:{
    
    
		key:'value',
	},
	method:'get'
}).then(res=>{
    
    })

post sends a request with parameters :

axios({
    
    
	url:'https://api',
	params:{
    
    
		key:'value',
	},
	method:'post'
}).then(res=>{
    
    })

If data is used instead of params to send, the value received in the background is null, because axios uses post to carry parameters by default using application/json.
Solution: 1. Use params 2. Add @requestBody to the request parameters on the server side.

3. Axios request method

get has no parameters :

axios.get('url').then(res=>{
    
    }).catch(err=>{
    
    })

get has parameters :

axios.get('url',{
    
    parmas:{
    
    key:'value'}}).then(res=>{
    
    }).catch(err=>{
    
    })

post without parameters :

axios.post('url').then(res=>{
    
    }).catch(err=>{
    
    })

The post has parameters :

axios.post('url',"key=value&key2=value2").then(res=>{
    
    }).catch(err=>{
    
    })

To transfer data using data, the background needs to automatically convert axuios into java objects, plus @requestBody.
insert image description here

4. Axios concurrent requests

An array of successful responses to requests.
You can use the spread function method to process the response result.

axios.all([
	axios.get('url'),
	axios.post('url')])
.then(
	axios.spread((res1,res2)=>{
    
    })
).catch(err=>{
    
    })

5. Global configuration

Specifies the default configuration, which will be applied to every request.

axios.defaults.baseURL='';
axios.defaults.timeout=2000;

6. Examples

Encapsulate different instances to achieve different configurations

let newVar=axios.create({
    
    
	baseURL:'',
	timeout:5000
});
newVar({
    
    
	url:''
}).then(res=>{
    
    })

7. Interceptor

Actions are processed before initiating a request or response, intercepting them before they are processed by then or catch. approximately equal to the filter

Axios two types of interceptors: interception in the request direction and interception in the response direction.

// 添加请求拦截器
axios.interceptors.request.use(config=>{
    
    
    // 在发送请求之前做些什么
    return config;
  }, error=>{
    
    
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(response=>{
    
    
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, error=>{
    
    
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

Remove the interceptor:

const myInterceptor = axios.interceptors.request.use(function () {
    
    /*...*/});
axios.interceptors.request.eject(myInterceptor);

8. Module encapsulation of axios in vue

  1. Installnpm install --save
  2. Create a request folder to store the request function;
  3. encapsulation.

Pass parameters:

import axios from 'axios';
export function request(config,success,fail){
    
    
	axios({
    
    
		url:config
	}).then(res=>{
    
    success();})
	.catch(err=>{
    
    fail();})
}

export function request1(config){
    
    
	axios.defaults,baseURL='';
	axios(config).then(res=>{
    
    config.success(res);})
	.catch(err=>{
    
    config.fail(err);})
	// config={url:'',success:res=>{},fail:err=>{}}
}

promise:

export function request(config){
    
    
	return new Promise((resolve,reject)=>{
    
    
		let newVar=axios.create({
    
    
			baseURL:'',
			timeout:5000
		});
		newVar(config).then(res=>	{
    
    resolve(res);}).catch(err=>{
    
    reject(err);})
	})
}
//调用
request({
    
    url:''}).then(res=>{
    
    }).catch(err=>{
    
    })

Create an instance:

export function request(config){
    
    
	let newVar=axios.create({
    
    
		baseURL:'',
		timeout:5000
	});
	return newVar(config);
}

request({
    
    
	url:''}).then(res=>{
    
    })

Ability to perform source code analysis

Guess you like

Origin blog.csdn.net/qq_46056318/article/details/127338993