Callback Hell
function loadImg(src,callback,fail){
var img = document.createElement('img')
img.onload = function(){ //图片加载成功
callback(img)
}
img.onerror = function(){ //图片加载失败
fail()
}
img.src = src
}
var src = 'http://www.imooc.com/static/img/index/logo_new.png'
loadImg(src,function(img){
console.log(img.width)
},function(){
console.log('failed')
})
Promise语法
function loadImg(src){
const promise = new Promise (function (resolve,reject){
var img = document.createElement('img')
img.onload = function(){
resolve(img)
}
img.onerror = function(){
reject()
}
img.src = src
})
return promise
}
var src = 'https://www.imooc.com/static/img/index/logo_new.png'
var result = loadImg(src)
result.then(function(img){
console.log(img.width)
},function(){
console.log('failed')
})
result.then(function(img){
console.log(img.height)
},function(){
console.log('failed')
})
总结
- new Promise实例,而且要return
- new Promise 时要传入函数,函数有 resolve reject 两个参数
- 成功时执行 resolve() 失败时执行 reject()
- then 监听结果
网友评论