function loadImg(src) {
const promise = new myPromise(function(resolve, reject){
let img = document.createElement("img");
img.onload = function() {
resolve(this);
} ;
img.onerror = function() {
reject();
}
img.src = src;
});
return promise;
}
const my = loadImg("https://img1.sycdn.imooc.com//55deec9c0001418c38402160-100-100.jpg");
my.then(function(){
console.log("ok1");
},function(){
console.log("error");
})
这里是不是因为img.onload是异步的,所以才会先执行then方法,然后resolve();
假如我这边换成这样:
function loadImg(src) {
const promise = new myPromise(function(resolve, reject){
if (true) {
resolve(this);
}
});
return promise;
}
const my = loadImg("https://img1.sycdn.imooc.com//55deec9c0001418c38402160-100-100.jpg");
my.then(function(){
console.log("ok1");
},function(){
console.log("error");
})
then里面的方法没有加载进入resolve就执行了;但是原生Promise不会出现这个问题