Promise

一. Promise概念

异步编程的一种解决方案

二. Promise用法

1. 异步请求

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	</body>
	<script>
		new Promise((resolve, reject) => {
			setTimeout(() => {
				resolve()
			}, 5000);
		})
		.then(()=>{
			console.log("1111111111111")
		});
		new Promise((resolve, reject) => {
			setTimeout(() => {
				resolve()
			}, 2000);
		})
		.then(()=>{
			console.log("2222222222222")
		});
	</script>
</html>

2. 防止回调地狱

1)回调地狱函数(层层嵌套,逻辑混乱)

new Promise((resolve, reject) => {
			setTimeout(() => {
				console.log("Hellow World")
				console.log("Hellow World")
				console.log("Hellow World")
				console.log("Hellow World")
				setTimeout(() => {
					console.log("Hellow Vue")
					console.log("Hellow Vue")
					console.log("Hellow Vue")
					console.log("Hellow Vue")
					setTimeout(() => {
						console.log("Hellow Java")
						console.log("Hellow Java")
						console.log("Hellow Java")
						console.log("Hellow Java")
					}, 1000);
				}, 1000);
			}, 1000);
		})

2)通过promise解决回调地狱

new Promise((resolve, reject) => {
	// 第一次网络请求的代码
	setTimeout(() => {
		resolve();
	}, 1000)
})
.then(() => {
	// 第一次拿到结果处理代码
	console.log("Hellow World")
	console.log("Hellow World")
	console.log("Hellow World")
	console.log("Hellow World")
	return new Promise((resolve, reject) => {
		//第二次网络请求的代码
		setTimeout(() => {
			resolve();
		}, 1000)
	})
})
.then(() => {
	//第二次拿到结果处理代码
	console.log("Hellow Vue")
	console.log("Hellow Vue")
	console.log("Hellow Vue")
	console.log("Hellow Vue")
	//第三次网络请求的代码
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve();
		}, 1000)
	})
})
.then(() => {
	//第三次拿到结果处理代码
	console.log("Hellow Java")
	console.log("Hellow Java")
	console.log("Hellow Java")
	console.log("Hellow Java")
})
上一篇:理解指针(三)-字符串与字符数组


下一篇:NOTE1:关于print() 10/01/2021-初学者