首先我们用js语法封装一个异步获取图片的函数
function loadImg(src,callback,fail){
var img = document.createElement('img');
img.onload=function() {
callback(img) //成功加载时...
}
img.onerror= function() {
fail() //没有加载时...
}
img.src = src;
}
调用该函数
var src="images/1.jpg"
loadImg(src,function(img) {
console.log(img.width)
},function(){
console.log('fail')
})
现在我们用promise改造这个函数
安照基本语法我的思路为:
1. new Promise实例,而且要return
2.new Promise时要传入函数,函数有resolve 和reject两个函数
3. 成功时执行resolve()失败时执行reject()
4.then 监听结果
function loadImg(src) {
const promise = new Promise(function (resolve,reject) {
var img = document.createElement('img');
img.onload = function() {
resolve(img)
}
img.onerror = function() {
reject()
}
})
return promise;
}
var src="images/1.jpg";
var result = loadImg(src);
result.then(function(img){
console.log(img.width); //此处放成功的回调
},function(){
console.log('fail'); //此处放失败信息
})
result.then(function(img){
console.log(img.height);
},function(){
console.log('fail');
})
下面是关于promise的异常捕获
异常捕获的规定只接收一个参数,最后统一用catch捕获异常
把上面栗子的then部分改为
result.then(function (img) {
console.log(img.width)//之前then接收两个参数,一个成功后的回调和一个失败后的回调,但此处只接收了成功的回调
}).then(function(){
console.log(img.height)
}).catch(function(ex){//catch捕获了回调的异常
console.log(ex)
})
可以看到有点像js原生捕获异常的try..catch方法
下面是多个串联
比如我们定义了多个图片
var src1 = "images/1.png";
var result1 = loadImg(src1);
var src2 = "images/2.png";
var result2 = loadImg(src2)
//链式操作
result1.then(function (img1) {
console.log("第一个图片加载完成..")
return result2;//返回result2然后才能紧接着调用result2
}).then(function (img2) {
console.log("第二个图片加载完成..")
}).catch(function (ex) {
console.log(ex)
})
下面是Promise.all和Promise.race
Promise.all接收一个promise对象的数组
等到全部完成之后,统一执行success
栗子
Promise.all([result1,result2]).then(datas => {//接收到的datas是一个数组,依次包含多个promise返回的内容
console.log(datas[0]);
console.log(datas[1]);
})
Promise.race接收一个包含多个promise对象的数组只要一个完成,就执行success
栗子
Promise.race([result1,result2]).then(data => {//接收到的datas是一个数组,依次包含多个promise返回的内容
console.log(data);
})