ES6基础知识总结4-Promise()

什么是Promise?

  • 承诺 Promise
  • 结果 :resolve兑现 reject拒绝
  • 凭据 then 然后 catch 捕获失败

随机输出两句话

var p = new Promise(function(resolve, reject) {
    
    
				setTimeout(() => {
    
    
					var n = Math.random();
					if (n > 0.5) {
    
    
						resolve('买别墅')
					} else {
    
    
						reject('等40岁')
					}
				}, 3000)
			})

			p.then(function(res) {
    
    
				console.log(res) //得到兑现
			}).catch(err => {
    
    
				console.error(err) //被拒绝延期
			})

promise的作用

  • 解决延期异步任务 避免回调层级过深

每隔一段时间输出一句话,用回调函数也可以解决,但层级过深,容易造成回调地狱,但用Promise可以解决这一问题

  • 用回调函数解决
function say(str, time, callback) {
    
    
				setTimeout(() => {
    
    
					console.log(str);
					if (callback) {
    
    
						callback();
					}
				}, time)
			}
			say('你好', 3000, function() {
    
    
				say('加个微信', 5000, function() {
    
    
					say('欢迎', 2000)
				})
			})

从上方可以看出回调函数,需要多个嵌套,当输出语句过多时太过于麻烦,层级过多。

  • 用Promise解决
function say(str,time){
    
    
				return new Promise((resolve,reject)=>{
    
    
					setTimeout(()=>{
    
    				
						resolve(str);
					},time)
				})
			}
			say('你好',3000)
			.then(res=>{
    
    
				console.log(res);
				return say('加个微信',5000)
			})
			.then(res=>{
    
    
				console.log(res);
				return say('欢迎',2000)
			})
			.then(res=>{
    
    
				console.log(res);
			})

Promise解决此类问题不需要多层嵌套,解决了层级过深的问题。

猜你喜欢

转载自blog.csdn.net/qq_45891136/article/details/108019622