[reject usage record]

This blog records the two callback methods of reject

  1. Use two functions in .then , and the second function corresponds to the reject content;
  2. use .catch ;

1. Use two functions in .then

function promiseClick(){
    
    
		let p = new Promise(function(resolve, reject){
    
    
			setTimeout(function(){
    
    
				var num = Math.ceil(Math.random()*20); //生成1-10的随机数
				console.log('随机数生成的值:',num)
				if(num<=10){
    
    
					resolve(num);
				}
				else{
    
    
					reject('数字太于10了即将执行失败回调');
				}
			}, 2000);
		   })
		   return p
	   }
 
	promiseClick().then(
		function(data){
    
    
			console.log('resolved成功回调');
			console.log('成功回调接受的值:',data);
		}, 
		function(reason){
    
    
			console.log('rejected失败回调');
			console.log('失败执行回调抛出失败原因:',reason);
		}
	);	

2. Use .catch

function promiseClick(){
    
    
		let p = new Promise(function(resolve, reject){
    
    
			setTimeout(function(){
    
    
				var num = Math.ceil(Math.random()*20); //生成1-10的随机数
				console.log('随机数生成的值:',num)
				if(num<=10){
    
    
					resolve(num);
				}
				else{
    
    
					reject('数字太于10了即将执行失败回调');
				}
			}, 2000);
		   })
		   return p
	   }
 
	promiseClick().then(
		function(data){
    
    
			console.log('resolved成功回调');
			console.log('成功回调接受的值:',data);
			console.log(noData);
		}
	)
	.catch(function(reason, data){
    
    
		console.log('catch到rejected失败回调');
		console.log('catch失败执行回调抛出失败原因:',reason);
	});	

Both of these can handle rejection, but when using the .catch method, you can receive the exception thrown by .then.
For example, the output of the second piece of code is:insert image description here

おすすめ

転載: blog.csdn.net/s_1024/article/details/128284645