<html>
<head>
<title>promise</title>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<h1>同步和异步 </h1>
<P>同步会阻塞 异步不会阻塞</P>
<P>异步用在网络请求ajax setTimeout</P>
<P>promise不是解决回调 是解决ajax多层嵌套</P>
</body>
</html>
<script src="../js/jquery.min.js"></script>
<script>
//手写promise 加载一张图片
function LoadImg(src) {
return new Promise(
(resolve, reject) => {
const img = document.createElement('img')
img.onload = () => { //定义异步正常执行
resolve(img)
}
img.onerror = () => {
const err = new Error(`图片加载失败 ${src}`)
reject(img)
}
img.src = src; //立刻执行渲染显示图片
}
)
}
const src1 = 'http://a4.att.hudong.com/21/09/01200000026352136359091694357.jpg'
const src2 = 'http://a1.att.hudong.com/05/00/01300000194285122188000535877.jpg'
LoadImg(src1).then(img => { //then 是promise的方法 resolve 的时候执行 catch 也是promise的方法 在reject的时候执行
console.log(img.height)
return img
}).then((img) => {
console.log(img.width)
return LoadImg(src2)
}).then((img) => {
console.log(img.height)
return img
}).then((img) => {
console.log(img.width)
}).catch((err) => {
console.log(err)
})
</script>