一分钟教你如何手写promise异步加载一张/多张图片
一、写在开头
最近一直在搞小程序,有点腻了,顺便复习了一下js,刚好可以写一个简单的promise回顾一下异步,见笑了各位。
二、发现问题
异步是js基础知识中的重要一环,也是有点难以理解,这里我手写了一个简单的图片加载示例,希望可以帮助各位回顾一下。
三、解决问题
异步主要抓住两点:
1.知道什么时候用return返回需要用的数据/调用的函数
2.知道什么时候监听什么函数来写对应的回调resolve(),reject()
以下是代码的简单示例:
<!DOCTYPE html>
<html>
<head>
<title>手写promise加载图片</title>
</head>
<body>
<script type="text/javascript">
const url1='https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3719520752,2657134858&fm=26&gp=0.jpg'//网上随便找一个图片的地址
const url2='https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3461776228,1302027451&fm=26&gp=0.jpg'
function loadImage(src){//定义一个异步加载图片的函数
const p = new Promise((resolve,reject)=>{//new一个promise对象
const img =document.createElement('img')//创建一个img节点
img.src=src//把我们的图片地址给我们新建的节点
img.onload=()=>{//通过监听节点成功建立(当然图片也传进去)调用resolve
resolve(img)//返回整个节点,可以用.then捕捉
}
img.onerror=()=>{//监听错误,可以用.catch捕捉
reject(`图片加载失败,地址为${src}`)
}
})
return p//记得把整个promise对象返回
}
loadImage(url1)//调用异步函数
.then((res)=>{//成功加载时
console.log(res.width);
return res;//把拿到的参数即图片节点返回出去,那么下一个then也能使用,如此避免回调地狱
})
.then((res)=>{
console.log(res.height);
})
.catch((err)=>{//发现错误时
console.log(err);
})
//以下是加载多个图片的情况(res和url1/url2没有区别,只是参数而已,可以随便取名字)
loadImage(url1)
.then((url1)=>{
console.log(url1.width);
return loadImage(url2);//返回出去就行了
})
.then((url2)=>{
console.log(url2.width);
})
</script>
</body>
</html>
好了,目前先到这,我是O5,希望能帮助到大家,共勉!