Preliminary understanding of Promise

First, we know Promise from console Dir (Promise) start

The prototype method in prototype needs an instance

all race reject resolve is a static method, which is used directly

How to use Promise?

new Promise((resolve,reject) => {
			setTimeout(() => {
				console.log('implement Promise')
				resolve('Data to return')
			},2000)
		})

This code just creates a Promise object and does not call resolve

We try to call the resolve method and print the parameters inside

	<div onclick="promiseClick()">Click I send asynchronous request</div>


	<script>
			
		function promiseClick(){
			let p = new Promise((resolve,reject) => {
				setTimeout(() => {
					console.log('123')
					resolve('456')
				},2000)
			});
			return p
		}
		
		promiseClick().then((data) => {
			console.log(data)
		})
		</script>

In the # promiseClick method, a Promise instance is returned. In this instance, there is a then method. The then method is the callback when Promise succeeds, which can also be written as

	function promiseClick(){
			 return new Promise((resolve,reject) => {
				setTimeout(() => {
					console.log('123')
					resolve('456')
				},2000)
			});
			 
		}
//The direct return new Promise instance has a similar effect as before

In fact, two callback functions can be written in then. The first is a successful callback function and the second is a failed callback function, as shown below

	function promiseClick(){
			new Promise((resolve,reject) => {
				setTimeout(() => {
					let num = Math.ceil(Math.random()*20)
					console.log('Random number:',num)
					if(num <= 10) {
						resolve('456')
					}else {
						reject('If the number is greater than 10, the callback failed to execute')
					}
				
					
				},2000)
			})
			.then((res1) => {
				console.log(res1)
			},
			(res2) => {
				console.log(res2)
			})
		
			;
		}

 

In addition to the then method, there is also the catch method. It is equivalent to the callback when Promise fails, which is the same as the second callback in then, but it also has more functions, that is, if there is an exception in then, it will run to catch

	function promiseClick(){
			new Promise((resolve,reject) => {
				setTimeout(() => {
					let num = Math.ceil(Math.random()*20)
					console.log('Random number:',num)
					if(num <= 10) {
						resolve('456')
					}else {
						reject('If the number is greater than 10, the callback failed to execute')
					}
				
					
				},2000)
			})
			.then((res) => {
				console.log(res)
				
			})
			.catch((res) => {
				console.log(res)
			})
			;
		}

Promise has a static method all

	<script>
			
		function promiseClick(){
			let p = new Promise((resolve,reject) => {
				setTimeout(() => {
					let num = Math.ceil(Math.random()*20)
					console.log('Random number:',num)
					if(num <= 10) {
						resolve('456')
					}else {
						reject('If the number is greater than 10, the callback failed to execute')
					}
				
					
				},2000)
			})
			return p
			
		}
		
		function promiseClick2(){
			let p = new Promise((resolve,reject) => {
				setTimeout(() => {
					let num = Math.ceil(Math.random()*20)
					console.log('Random number:',num)
					if(num <= 10) {
						resolve('456')
					}else {
						reject('If the number is greater than 10, the callback failed to execute')
					}
				
					
				},2000)
			})
		
		return p
			
		}
		
		function promiseClick3(){
			let p = new Promise((resolve,reject) => {
				setTimeout(() => {
					let num = Math.ceil(Math.random()*20)
					console.log('Random number:',num)
					if(num <= 10) {
						resolve('456')
					}else {
						reject('If the number is greater than 10, the callback failed to execute')
					}
				
					
				},2000)
			})
		return p
			
		}
		
		Promise.all([promiseClick(),promiseClick2(),promiseClick3()])
		.then((res) => {
			console.log(res)
		})
		
	
		</script>

Promise.all() passes an array, then: if it succeeds, the result will be printed, and the result is also an array

If one of # promiseClick, promiseClick2 and promiseClick3 goes, reject will report an error and cannot get the last array

In fact, I still don't know the use of promise here. Let's continue to look down

setTimeout(()=> {
			console.log('I')
			setTimeout(() => {
				console.log('love')
				setTimeout(() => {
					console.log('Rice')
				},1000)
			},1000)
		},1000)

 

Print every second. Do you think it's good to write like this? (is there too much nesting? This is only 3 layers. What if it is 30 layers?)

Now try Promise

		function getStr(){
			return new Promise((resolve,reject) => {
				setTimeout(() => resolve('I'),1000)
			})
		}
		function getStr2(){
			return new Promise((resolve,reject) => {
				setTimeout(() => resolve('love'),1000)
			})
		}
		function getStr3(){
			return new Promise((resolve,reject) => {
				setTimeout(() => resolve('Rice'),1000)
			})
		}
		/* Chain operation */
		getStr().then((res) => {
			console.log(res)
			return getStr2()
		}).then(res => {
			console.log(res)
			return getStr3()
		}).then(res => {
			console.log(res)
		})

The same effect is achieved. Note that this is a chain operation. The first then of getStr is successful. Come here, print the carried data, and return getStr2, which means to call getStr2. If getStr2 succeeds, go to his then, and return getStr3 in the then of getStr2. Although there are many codes, isn't it better?

Finally, a case is attached

	
	/* 
	b Request data dependent on a 
	 */
		
		function a(){
		      return new Promise(function(res,rej){
		        $.ajax({
		          url:"a Interface",
		          type: "GET",
		          async:true,
		          dataType:"json",
		          success:function(data){
		            console.log(data,"a");
		            res(data);
		          }
		        })
		      });
		    }
		    function b(data){
		      console.log(data,"data");
		      return new Promise(function(res,rej){
		        $.ajax({
		            url:"b Interface",
		            type: "POST",
		            async:true,
		            data:JSON.stringify(data),
		            dataType:"json",
		            success:function(data){
		              console.log(data,"b");
		              res();
		            }
		          })
		      });
		    }
		    $("#btn").click(function(){
		      a().then(function (data){
		        b(data);
		      }).then(function(){
		      })
		    })

	

In the later stage, connect axios

Keywords: Javascript Front-end Vue.js

Added by IronicSoul on Tue, 25 Jan 2022 00:55:44 +0200