仅展示封装,详细看原生js 同步&异步的Promise板块。
class Promise1 {
status = "pending";
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this));
}
resolve(result) {
if (this.status !== "pending") return;
var ids = setTimeout((function () {
this.setVal("resolve", result);
clearTimeout(ids);
}).bind(this), 0);
}
reject(error) {
if (this.status !== "pending") return;
var ids = setTimeout((function () {
this.setVal("reject", error);
clearTimeout(ids);
}).bind(this), 0);
}
then(_resolve, _reject) {
this._resolve = _resolve;
this._reject = _reject;
}
catch(_reject) {
this._reject = _reject;
}
setVal(_status, arg) {
this.status = _status;
if (_status === "resolve" && this._resolve) {
this._resolve(arg);
} else if (_status === "reject" && this._reject) {
this._reject(arg);
}
}
}
// // 创建-实例化对象
// var p = new Promise1(function (resolve, reject) {
// var img = new Image();
// img.src = "./img/3-.jpg";
// img.onload = function () {
// resolve(img);
// }
// img.onerror = function () {
// reject(img.src);
// }
// })
// // 使用
// p.then(function (img) {
// console.log(img);
// }, function (msg) {
// console.log(msg);
// })
// 创建-函数式
function loadImage(){
return new Promise1(function(resolve,reject){
var img=new Image();
img.src="./img/3-.jpg";
img.onload=function(){
resolve(img);
}
img.onerror=function(){
reject(img.src);
}
})
}
// 使用
loadImage().then(function(img){
console.log(img);
},function(msg){
console.log(msg);
})
后补-------------------------
class MyPromise {
status = "pending";
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this));
}
resolve(result){
if(this.status!=="pending")return;
let ids=setTimeout((function(){
this.setVal("resolve",result);
clearTimeout(ids);
}).bind(this),0)
}
reject(error){
if(this.status!=="pending")return;
let ids=setTimeout((function(){
this.setVal("reject",error);
clearTimeout(ids);
}).bind(this),0)
}
then(_resolve,_reject){
this._resolve=_resolve;
this._reject=_reject;
return this;
}
catch(_reject){
this._reject=_reject;
return this;
}
setVal(_status,arg){
this.status=_status;
if(_status==="resolve"&&this._resolve){
this._resolve(arg);
}else if(_status==="reject"&&this._reject){
this._reject(arg);
}
}
}
// 图片预加载
// 定义
function loadImg(){
return new MyPromise((resolve,reject)=>{
let img =new Image();
img.src="./img/timg.jpg";
img.onload=function(){
resolve(img)
}
img.onerror=function(){
reject(img.src)
}
})
}
// 使用方式一
// loadImg().then(function(img){
// console.log(img);
// },function(msg){
// console.log(msg);
// })
// 使用方式二
loadImg().then((image)=>{
console.log(image)
}).catch((err)=>{
console.log(err);
})
console.log("-------")//能发现这行代码先打印
能发现console.log("-------")
这行代码先打印,因为promise是异步的,上面使用延时器就是为了保证代码的执行顺序,让resolve和reject的处理异步执行。