一分鐘教你如何手寫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,希望能幫助到大家,共勉!