面试题之:Promise的前世今生

jquery中ajax的几种方法如下:

	// 方案1
    var ajax = $.ajax({
      url: './1.json',
      success: function() {
        console.log(1);
        console.log(2);
        console.log(3);
      },
      error: function() {
        console.log('err')
      }
    })
    // 方案2
    var ajax = $.ajax('./1.json');
    ajax.done(function() {
      console.log('done1')
    }).fail(function() {
      console.log('fail1')
    }).done(function() {
      console.log('done2')
    }).fail(function() {
      console.log('fail1')
    }).done(function() {
      console.log('done3')
    }).fail(function() {
      console.log('fail1')
    })
    // 方案3
    var ajax = $.ajax('./1.json');
    ajax.then(function() {
      console.log('then1')
    }, function() {
      console.log('catch1')
    }).then(function() {
      console.log('then2')
    }, function() {
      console.log('catch1')
    }).then(function() {
      console.log('then3')
    }, function() {
      console.log('catch1')
    })

jquery中的promise雏形: Deferred

以上都是靠Deferred实现的。那么deferred到底是个什么东西呢?如何考deferred来结局异步呢?

  1. 声明一个函数
  2. 声明一个$.deferred实例
  3. 声明一个wait函数,传入dtd,对dtd进行操作
  4. 把dtdreturn出来

具体代码如下:

var waitHandle = function() {
	var dtd = $.Deferred();
	var wait = function(dtd) {
		setTimeout(function() {
			console.log('执行完成')
			dtd.resolve() //执行成功的回调
			dtd.reject() //执行失败的回调
		}, 1000)
	}
	return dtd.promise()
}

var w = waitHandle()

$.when(w).then(function() {
	//执行成功的函数
}, function() {
	//执行失败的回调函数
})

注意点:

  1. promise和deferred的区别是: promise把resolve和reject在函数外部过滤了。
  2. dtd.resolve 和dtd.reject() 同时只能执行1个

规范化: promise

基本语法

function loadImg(src) {
	const promise = new Promise((resolve, reject) => {
		var img = document.createElement('img')
		img.onload = function() {
			resolve(img)
		}
		img.onerror = function() {
			reject()
		}
		img.src = src
	})
	return promise
}
var src = "xxx"
var result = loadImg(src)
result.then(function(img) {
	console.log(img.width)
}, function() {
	console.log("faild")
})
result.then(function(img) {
	console.log("height")
})

异步语法

result.then(function() {
	//代码
}).then(function() {
	//代码
}).catch(function(ex) {
	//统一处理错误
	console.log(ex)
})

串联运行

加入有两个ajax请求,一个请求要在另外一个请求之后执行应该怎么处理?
在第一个要执行的promise里面返回第二个promise。
代码如下:

function loadImg(src) {
	const promise = new Promise((resolve, reject) => {
		var img = document.createElement('img')
		img.onload = function() {
			resolve(img)
		}
		img.onerroe = function() {
			reject()
		}
		img.src = src
	})
	return promise
}

//调用promise函数

var src1 = "...png"
var result1 = loadImg(src1)
var src2 = "...jpg"
var result2 = loadImg(src2)

result1.then(function() {
//result1的回调函数
	console.log('图片1执行成功')
	return result2
}).then(function() {
//result2的回调函数
	console.log('图片2执行成功')
}).catch() {
	console.log('error')
}
	

promise.all && promise.race

  1. promise.all 和 promise.race 都接受一个promise的数组
  2. all 是所有的promise都执行完了才then
  3. race 是只要有一个promise执行完成了就执行then
  4. all 返回一个datas的数组,是所有promise返回的集合
  5. race 返回data是第一个执行的Promise的结果

代码如下:

Promise.all([ promise1, promise2]).then(function(datas) {
	console.log(datas[1])
	console.log(datas[2])
})
Promise.race([promise1, promise2]).then((data) => {
	console.log(data)
})

promise标准

任何技术推广都需要一套标准来支撑

promise的状态

  1. pending 初始状态
  2. fulfilled 成功状态
  3. rejected 失败状态

promise的then

  1. 必须执行
  2. 接受两个参数
  3. 返回的必须是一个promise实例
  4. 如果没有返回值,返回的就是promise本身的实例

猜你喜欢

转载自blog.csdn.net/weixin_40814356/article/details/84163258