当前位置:网站首页>Simple use of promise in uniapp

Simple use of promise in uniapp

2022-07-06 08:42:00 Rookie post station 2020

Promise Take two functions as arguments , from Javascript The engine provides , Don't deploy yourself .
resolve Success function | reject Failure function

resolve(): Make current Promise The state of the object is changed to fulfilled
reject(): Make current Promise The object state is changed to rejected
Promise The change of state is one-off , That is to say resolve Function will not be executed reject Function .

var n = 0
// Instantiation  promise
let promise = new Promise(function(resolve, reject) {
    
	// Time consuming tasks , Use... In this example setTimeout(...) To simulate asynchronous code  
	setTimeout(function(){
    
		if(n%2 === 0){
    
			resolve(n)
			n = n+1
		}else{
    
			reject(n%2)
			n = n+1
		}
	}, 1000)					
})

// Method of calling instance 
promise.then(result =>{
    
	// When Promise The state of is fulfilled When the 
	console.log(' success '+ result)	
}).catch(error =>{
    
	//1.  When Promise Change the status of rejcted , Be performed 
	//2.  When Promise When there is an error in the actuator , Be performed 
	console.log(' Failure '+ error)	
}).finally(()=>{
    
	console.log(" success - Failure - All implemented ")
})	

 Insert picture description here
The other is to call functions

click1() {
    				
	this.PR1().then(result => {
    					
		console.log('resolved Successful callback ')
		console.log(' Successfully callback accepted value :', result)					
	}).catch(error => {
    					
		console.log('catch Failed execution callback throw failure reason :', error)					
	})			 
},
PR1() {
    
	let p = new Promise(function(resolve, reject) {
    
		setTimeout(function() {
    
			var num = Math.ceil(Math.random() * 20) // Generate 1-20 The random number 
			console.log(' Values generated by random numbers :', num)
			if (num <= 10) {
    
				resolve(num)
			} else {
    
				reject(' Number is greater than 10 About to execute the failed callback ')
			}
		}, 1000)		
	})
	return p
}

 Insert picture description here

原网站

版权声明
本文为[Rookie post station 2020]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060841160904.html