Promise
回调地狱
var base = 0; var img = new Image(); img.src = "./images/3-.jpg"; img.onload = function(){ base += img.width; var img1 = new Image(); img1.src = "./images/4-.jpg"; img1.onload = function(){ base += img1.width; var img2 = new Image(); img2.src = "./images/5.jpg"; img2.onload = function(){ base += img2.width; console.log(base); } } }
使用函数式编程解决回调地狱
var base = 0; init(); function init(){ var img = new Image(); img.onload = loadHandler; img.src = "./images/3-.jpg"; } function loadHandler(e){ base += this.width; if(this.src.indexOf("3-.jpg")>-1){ this.src = "./images/4-.jpg"; }else if(this.src.indexOf("4-.jpg")>-1){ this.src = "./images/5-.jpg"; console.log(base); } }
非函数式编程只能使用Promise解决回调地狱
// resolve是成功时要执行的回调函数 // reject是失败时要执行的回调函数 /* var p=new Promise(function(resolve,reject){ var img=new Image(); img.src="./img/3-.jpg"; img.onload=function(){ // resolve函数可以带入一个参数 resolve(img); } img.onerror=function(){ // reject函数也可以带入一个参数 reject(img.src); } }) */ p.then(function(img){ // reslove调用 console.log(img); },function(src){ // reject调用 console.log(src); })
简单封装下Promise
class Promise{ status = "pending"; constructor(fn){ console.log(this); fn(this.resolve,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); } } } function loadImage(){ return new Promise(function(resolve,reject){ var img = new Image(); img.src = "./images/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); });
相关推荐
nmgxzm00 2020-11-10
xixixi 2020-11-11
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
whynotgonow 2020-08-19
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13
88520191 2020-06-13
89500297 2020-06-13