ES6 深入理解之Promise篇(无限回调、throw、race、all、自动选项卡)

写在开头

本文将带你深入理解之Promise篇

后续的文章都会与前端有关,欢迎各位同路途的人一起交流学习,3月份又是努力的开头,加油!

推荐阅读:来自 菜鸟 的 前端实习面经 大厂 春招实习生

ES 6专栏 -> 传送门

如果想更多了解ES6,请参考之前写过的一些文章:

ES6 一文弄懂 var let const 三剑客区别 吊打面试题

ES6 面试题:你能说出浏览器上到此支持多少个中文字吗?

ES6 面试题:你可以写出一百个 div 吗?一万个呢?

ES6 深入理解 includes

ES6 深入理解 startsWith和endsWith

ES6 深入理解 ${ } 模版

ES6 深入理解 数组中 find 方法

ES6 深入理解 …拓展运算符 合并数组及demo选项卡实例

ES6 在es6中自定义封装 jQuery

ES6 深入理解之字符串篇 保姆级 教你用js写选项卡demo

ES6 深入理解之number篇 保姆级 教你用js写选项卡demo

ES6 深入理解之方法篇 保姆级 教你用js写选项卡demo

ES5 中的 严格模式

ES5 中的一些拓展

ES6 手把手教你环境配置与介绍(兼容ES5)

ES6 变量声明、解构赋值、模板字符串

ES6 箭头函数、参数默认值、拓展运算符、rest运算符

ES6 Promise、Symbol、async函数

ES6 字符串的拓展、数组的拓展、对象的拓展

Pending、Resolved(决定)、Rejected(拒绝)

then

new Promise(function(Resolved,reject){
	Resolved();
	reject();
}).then(function(){
	alert('成功')
},function(){
	alert('失败')
})

Promise 是个对象
类似 一个事情
事情 就会 有 成功 或者 失败
只要触发一个 这个函数就完成了自己任务

类似于 jquery 中 one 只执行一次

then catch

new Promise(function(Resolved,reject){
	Resolved('hehehehe');
	//reject();
}).then(function(x){
	console.log(x)
}).catch(function(){
	console.log('2313213')
})

封装

function showPromise(res){
	return new Promise((resolve,reject)=>{
		resolve(res)
	}).then((x)=>{console.log(x)},()=>{

	})
}

showPromise('666');
showPromise('123');
showPromise('哈哈哈');

promise的无限回调

promise 厉害之处就是能无限的回调

new Promise(function(Resolved,reject){
	Resolved('hehehehe');
}).then(function(x){
	alert(x);
	return 'ashkdajs';
}).then(function(x){
	alert(x);
	return '101010'
}).then(function(x){
	alert(x);
})



用promise写一个简易显示隐藏卡片

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title>
	<style type="text/css">
		#{
			margin: 0;
			padding: 0;
			list-style: none;
		}
		div{
			width: 200px;
			height: 200px;
			background: #CCCCCC;
			display: block;
		}
	</style>
</head>
<body>
	<input type="button"  id="ipt" value="显示/隐藏" />
	<div id="div1"></div>
<script type="text/javascript">
	let cc=0;
	ipt.onclick = x =>{
		cc++;
		new Promise((success,error)=>{
			cc%2==1?success():error();
		}).then(()=>{
			div1.style.display="block";
		}).catch(()=>{
			div1.style.display="none";
		})
	}
</script>
</body>
</html>

throw 抛出异常

抛出 异常throw ‘出大事了 下面就别执行了’

类似的有:

console.error();

console.warn();

		throw '抛出异常'

race 竞速方法

race ->只看第一个promise 成功就成功 ,失败就失败

	Promise.race([new Promise((succ,error)=>{
		//succ('12312');
		setTimeout(error,1000,'1');
	}),new Promise((succ,error)=>{
		setTimeout(succ,1200,'2');
	}),new Promise((succ,error)=>{
		setTimeout(succ,1400,'3');
	})]).then((x)=>{
		console.log(x+'suss');
	
	},(x)=>{
		console.log(x+'error')
	})

在这里插入图片描述

all 规整方法

all ->要不然就是全胜 要不然就是 失败

Promise.all([new Promise((succ,error)=>{
	setTimeout(succ,1000);
}),new Promise((succ,error)=>{
	setTimeout(succ,2000);
}),new Promise((succ,error)=>{
	setTimeout(error,1000);
})]).then(()=>{
	console.log('成功!')
}).catch(()=>{
	console.log('失败')
})

reject

	Promise.reject(['1','2']).then((f,x)=>{
		//console.log(x)
	}).catch((a)=>{
		console.log(a)
	})

自动选项卡 demo

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title></title> 
    <style type="text/css">
input.active{
	background: red;
}

.outNode>div{width: 200px;height: 200px;background: #ccc;display: none;}
.outNode>div:first-of-type{
	display: block;
}

    </style>
</head>
<body>
<script type="text/javascript">


const $=obj=>[...document.querySelectorAll(obj)];
const jsonDate={
	'vlaueName':['小黑','小白','小红'],
	'innnerHtml':[
		'变黑了','变瘦了','变高了'
	]
};
let Index = 0;
const createNode=json=>`<div class=outNode>
	${json.vlaueName.map((x)=>`<input type=button value=${x}>`).join('')}
	${json.innnerHtml.map((x)=>`
		<div>${x}</div>
		`).join('')}
</div>`;

document.body.innerHTML = createNode(jsonDate);
let allInput = new Set($('input'));
let allDiv = new Set($('.outNode>div'));
[...allInput][0].className = 'active';
[...allInput].forEach((x,y)=>{
	x['onclick']=()=>{
		[...allDiv].forEach(f=>f.style.display='none');
		[...allDiv][y].style.display = 'block';
	}
});

setInterval(()=>{
	Index++;
	(Index == [...allInput].length) &&(Index=0);
	[...allInput].forEach(x=>x.className='');
	[...allInput][Index].className = 'active';
	[...allDiv].forEach(x=>x.style.display='none');
	[...allDiv][Index].style.display = 'block';
},1000);

</script>
</body>
</html>

总结

Pending、Resolved(决定)、Rejected(拒绝)
catch
race 竞速方法
all 规整方法

学如逆水行舟,不进则退
发布了572 篇原创文章 · 获赞 1651 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/104691495
今日推荐